C language: A number is called a perfect number if it is exactly equal to the sum of its factors except itself. For example, 6=1+2+3. Program to find all perfect numbers within 1000.

analyze:

    In the main function main, the program first defines three integer variables m, s and i, which are used to calculate and determine the completion number. Then use the printf function to output the prompt information.

    Next, the program uses a for loop structure to iterate through all numbers from 2 to 999. For each traversed number m, the program initializes the variable s to 0.

    Then, the program uses another for loop structure to iterate through all numbers less than m from 1 to m-1. For each traversed number i, the program determines whether i is a factor of m (that is, m can be divided by i) through the if conditional judgment statement. If true, add i to s.

    After the first for loop ends, the program judges whether s is equal to m through the if conditional judgment statement. If the judgment is true, that is, s is equal to m, it means that m is a perfect number. At this time, the program uses the printf function to output the perfect number, and uses the third for loop to output the factors of the perfect number.

    Finally, the program uses the printf function to output a newline character, indicating the end of output.

Code:

#include<stdio.h>
int main()
{
	int m,s,i;
	for(m=2;m<1000;m++)
	{
		s=0;
		for(i=1;i<m;i++)
			if((m%i)==0) s=s+i;
			if(s==m)
			{printf("%d,its factors are",m);
			for(i=1;i<m;i++)
				if(m%i==0) printf("%d ",i);
				printf("\n");
			}
	}
	return 0;
}

operation result:

Guess you like

Origin blog.csdn.net/m0_63002183/article/details/134627395