perfect.c (889B)
1 /* Exercise 5.26 */ 2 3 /* 4 Time results with "n <= 100000": 5 6 6: 1 2 3 = 6 7 28: 1 2 4 7 14 = 28 8 496: 1 2 4 8 16 31 62 124 248 = 496 9 8128: 1 2 4 8 16 32 64 127 254 508 1016 2032 4064 = 8128 10 11 166.42s real 159.95s user 0.00s system 12 */ 13 14 #include <stdio.h> 15 16 int perfect(int); 17 18 int main() 19 { 20 int n, s, f; 21 22 for(n = 1; n <= 100000; n++) { 23 if(perfect(n)) { 24 printf("%d: ", n); 25 for(s = 1, f = 0; s < n; s++) { 26 if( !(n % s) ) { 27 printf("%d ", s); 28 f += s; 29 } 30 } 31 printf("= %d\n", f); 32 } 33 } /* end for (n) */ 34 35 return 0; 36 37 } /* E0F main */ 38 39 /* check if num is a perfect number */ 40 int perfect(int num) 41 { 42 int i, f_sum = 0; 43 44 /* check its factors */ 45 for(i = 1; i < num; i++) { 46 if( !(num % i) ) { 47 /* num is multiple of i */ 48 f_sum += i; 49 } 50 } 51 52 if(f_sum == num) return 1; 53 54 return 0; 55 } /* eof perfect() */ 56