Violent solution - complete number (equal to the sum of factors other than itself)

Find all perfect numbers among natural numbers within 10,000, and count the number of perfect numbers found.

#include<stdio.h>
int main()
{
	//找到10000以内所有的完数(等于恰好等于它本身之外的因子之和),并统计完数个数。
	int n,i,s,count=0;
	printf("找到的所有完数:\n"); 
	for(n=1;n<10000;n++)
	{
		s=0;
		for(i=1;i<n;i++)
		{
			if(n%i==0)
			{
				s+=i;		
			}
		}
		if(s==n)
			{
				printf("%d ",n);
				count++;
			}
	}
	printf("完数个数为%d.\n",count); 
	return 0;
}

        Perform a modulo operation on every number within 10000 to determine whether i is a factor of this number. If it is a factor of this number, then add this factor to s. Finally, if s is equal to this number, then this number is complete. number!

        To optimize this program, first find the factors. Factors appear in pairs. If a factor appears in less than or equal to \sqrt{n}, then it will appear in greater than \sqrt{n}There must also be a corresponding factor. Note: If n=m^2, factors will not appear in pairs. For example, n=36, the factors are 1,2,3,4,6,9,12,18,36, and factor 6 only appears once.

Yus+=i+n/i;

So ifn=m^2 in the program, then i and n/i will be equal, that is, the factor is repeated once, and this factor needs to be subtracted once.

#include<stdio.h>
#include<math.h> 
int main()
{
	int n,i,s,m,count=0;
	printf("找到的完数有:\n");
	for(n=2;n<10000;n++)
	{
		s=1;
		m=sqrt(n);
		for(i=2;i<=m;i++)
		{
			if(n%i==0)
			{
				s+=i+n/i;	
			}
		}
		if(n==m*m)
		{
			s-=m;
		}
		if(s==n)
		{
			printf("%d, ",n);
			count++;
		}
	} 
	
	printf("\n完数个数为%d\n",count);
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_55848732/article/details/131999819