C language judges the perfect number and outputs its factor

A number is said to be perfect if it is exactly equal to the sum of its factors. For example, the factors of 6 are 1, 2, 3, and 6=1+2+3, so 6 is a perfect number, please program to find the perfect number within 1000, and output it in the following format.
6 its factors are 1 2 3,
0, 1 is not a complete number.
Problem-solving ideas: We can create a variable to store the sum of the factors of the number we are looking for. If the number is exactly equal to the sum of its factors, then just print out all its factors.
Source code:
#include<stdio.h>
int main()
{ int i = 0;

for ( i = 2; i <= 1000 ; i++)
{		
	int sum = 0;//存放所有因子之和
	for (int j = 1; j < i; j++)
	{
		if (i%j == 0)
		{
			sum += j;
		}
	}
	if (i == sum)//如果sum==i说明i是完数
	{
		printf("%d its factors are:", i);
		for (int j = 1; j < i; j++)//找出i所有的因子,并打印
		{
			if (i%j == 0)
			{
				printf("%d ", j);
				
			}
			
		}
		printf("\n");

	}
	
	

}	
return 0;

}

Guess you like

Origin blog.csdn.net/Kirihara_Yukiho/article/details/123245765