请高手帮忙编个c++的小程序。谢谢!

来源:百度知道 编辑:UC知道 时间:2024/06/22 01:00:58
A perfect number n is any positive integer that is equal to the sum of its divisors < n. For instance, 6 is a
perfect number. Indeed the divisors of 6 are 1, 2, 3 and 1 + 2 + 3 = 6. The next perfect number is 28 as 28
= 1 + 2 + 4 + 7 + 14.

Write a function sumOfDivisors that takes integer n as the parameter as returns the sum of all n’s
divisors < n.

Write a program to call this function. The program should read a positive integer and display if the integer
is a perfect integer.

Some examples of the execution of the program are as follows. Example 1
Enter a positive integer: 28
28 is a perfect number.
Example 2
Enter a positive integer: 20
20 is not a perfect number.

#include <iostream>
using namespace std;

bool perfect(int n)
{
int sum=0,m;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
m=i;
sum+=m;
if(sum==n)
{
return true;
}
}
}
return false;
}

void main()
{
int n;
cout<<"Enter a positive integer:";
cin>>n;
if(perfect(n))
cout<<n <<"is a perfect number."<<endl;
else
cout<<n<<" is not a perfect number."<<endl;
}

题目的意思是说:
我们把一种数字叫做“perfect number”,是怎么样的数字呢?
就是这样:如果对于n,他的所有约数,也就是所有能够把它整除的数字,他的这些约数如果加起来等于他自己,也就是n,那么输出 n is a perfect number,否则就不是。

注明:比如说6,他的约数有1,2,3。这里不包括他自己.并且1+2+3刚好等于6
比如28.他的约数有1,2,4,7,14这五个,并且1+2+4+7+14刚好等于28
那就输出n is a perfect number.

比如20.他的约数有1,2,4,5,10, 1+2+4+5+10不等于20,那就输出n is not a perfect number

我提