<span style= "Font-size:24px;color: #ff0000;" >/* Complete Number (Perfect number), also known as the perfect or complete number, is a number of special natural numbers. The sum of all its true factors (i.e., the factor function) is exactly equal to itself. For example, the first complete number is 6, it has an approximate 1, 2, 3, 6, except it itself 6, the remaining 3 numbers are added, 1+2+3=6. The second complete number is 28, it has approximate 1, 2, 4, 7, 14, 28, except it itself 28, the remaining 5 numbers added, 1+2+4+7+14=28. Programming to find a complete number within 10000. */#include <stdio.h> #define RANGE 10000 //Find the maximum range of # define Strlenth //The range of the array that holds the true factor bool Is_perfect_num (int n) {int array[strlenth];//The array that holds the true factor int count = 0; The number of true factors int total = 0; True factor addition and/* store the true factor in the array */for (int i=1;i<n;++i) {if (n%i = = 0) {array[count++] = i;//count++;}} /* Calculate all true factors and */for (i=0;i<count;++i) {total + = Array[i];} if (total = = N)//return true;//If it is a complete number, return ture otherwise return false//else//return false;return (total = = n);} int main () {for (int i=1;i<=range;++i) {if (Is_perfect_num (i)) printf ("%d\n", I);} return 0;} </span>
The above code, the efficiency is not high (when approximate, each Judge 1--n-1), and waste storage space (used in the array)
The revised code is as follows:
/*6: (1,6) (2,3)----> Start repeating---> (3,2): (1,12) (2,6) (3,4)----> Start repeating---> (4,3) (6,2) that is: N=a*b (a<=b) 36=6*6---->a,b is the true factor of n------>>>> start repeating when b>a */#include <stdio.h> #define RANGE 10000 / /Find the maximum range of bool Is_perfect_num (int n) {int total = 0; The sum of the factors (approximate) and int a = 1; First pair factor (approximate) int b = N;while (a < b) //not repeated {if (n%a = = 0) {Total + = A+b;//a,b is n factor, add to total}a++;//prepare for next judgment B = N/A;} /*a,b equal case, only add once, so can not be placed in the upper while loop, you have to consider */if (a = = b && A*b = = N) {total + = A;} /* Note that the return statement is more concise than if else, which is itself a Boolean type */return (total-n = = n);//Seek all true factors and, therefore, subtract}int main () {for (int i=1;i<=range; ++i) {if (Is_perfect_num (i)) printf ("%d\n", I);} return 0;}
Full number Perfectnumber