完全数,又称完美数或完数(Perfect Number),它是指这样的一些特殊的自然数,它所有的真因子(即除了自身以外的约数)的和,恰好等于它本身。例如,6就是一个完全数,是因为6 = 1 + 2 + 3。请编写一个判断完全数的函数IsPerfect(),然后判断从键盘输入的整数是否是完全数。注意:1没有真因子,所以不是完全数。
#include <stdio.h>
#include <math.h>
int IsPerfect(int x);
int main()
{
int m;
printf("Input m:");
scanf("%d", &m);
//
if(m > 1)
{
if (IsPerfect(m) == 1) /* 完全数判定 */
{
printf("%d is a perfect number\n", m);
}
else
{
printf("%d is not a perfect number\n", m);
}
}
else
{
printf("data error!\n");
}
//
return 0;
}
/* 函数功能:判断完全数,若函数返回0,则代表不是完全数,若返回1,则代表是完全数 */
int IsPerfect(int x)//x > 1
{
int i;
int total = 0; /* 1没有真因子,不是完全数 */
//
for (i =1; i < x; i ++)
{
if (x % i == 0)
total = total + i;
}
//
return total==x ? 1 : 0;
}