Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 1 of 1
Thread: C question Amicable numbers

11042013, 12:04 PM #1
 Join Date
 Nov 2013
 Posts
 1
 Thanks
 0
 Thanked 0 Times in 0 Posts
C question Amicable numbers
a)Write a procedure void fill (int * x, int len) . User loads
integer k, and then with random numbers from
segment [1, k] fill a array x that has a length len…
b)Two numbers are amicable if they have the same number of odd digits. For example, numbers 1245 i 22 are amicable, but 23 i 5 are not amicable… Write a C function NumberOfAmicables(int *x, int n) which returns how many sets with three amicable members are there.. For example.. If array is {12,235,5,51,128,777,4}, function returns 1 because sets with three amicable members are: (12,235,4)..
I'm thinking about doing it this way, but are there any better, simply methods? Please help me. Thanks in advance.
Code:void Fill(int *x, int len) { int k; printf("Enter the number k: "); scanf("%d", &k); int i; for (i=0; i<len; i++) { x[i] = rand() % k + 1; } } int Amicable(int a, int b) { int br1=0; int br2=0; while (a!=0) { if((a%10)%2==0) { br1++; } a=a/10; } while (b!=0) { if((b%10)%2==0) { br2++; } b=b/10; } if (br1==br2) { return 1; } else { return 0; } } int NumberOfAmicables(int *x, int n) { int i=0; int j=0; int k=0; int br=0; for (i=0; i<n; i++) { for (j=i+1; j<n; j++) { for(k=j+1;k<n;k++) { if (Amicable(x[i], x[j])&&Amicable(x[i],x[k])) { br++; printf("(%d, %d, %d), ", x[i], x[j], x[k]); } } } } return br; } int main() { int len=0; printf("Len. of array? : "); scanf("%d", &len); int* x = malloc(len*sizeof(int)); Fill(x, len); printf("Number of sets with three amicable members :%d\n", NumberOfAmicables(x,len)); return 0; }