SETHA SITE INFORMATION

  • Increase font size
  • Default font size
  • Decrease font size

How to get perfect number in C++?

E-mail Print PDF
This article shows you the C++ code to display perfect number between two defined numbers.
A perfect number is a positive integer that is equal to the sum of its proper positive divisors excluding the number itself.
Example: 28=1+2+4+7+14
void showPerfectNumber(int start_n, int end_n)
{
	int s, k;
	int d[5000];
	for(int i=start_n; i<=end_n; i++)
	{
		s=0;
		k=0;
		d[k]='\0';
		for(int j=1; j<=i/2; j++)
		{
			if(i%j==0)
			{
				s+=j;	
				d[k]=j;
				k+=1;
			}
		}
		if(s==i) 
		{
			printf("%d is perfect. Its divisors are\n",i);
			for(int i=0;i<k;i++)
			{
				printf("%d",d[i]);
				if(i<k-1) printf(", ");
			}
			printf("\n");
		}
	}
}

  Download Source Code Here