C++编程第19题

//一个数如果恰好等于它的因子之和,这个数就称为“完数”。
//例如6=1+2+3.编程找出1000以内的所有完数。
//注意是所有因子,而非质因子

#include <iostream>

using namespace std;

int main()
{
    int n,tran,t;
    static int count[10];
    //该数组用来保存质因子,因为10个2相乘为1024,所以定义数组大小为10
    for(n=2;n<1000;n++){
        t=-1;
        tran=n;
        for(int i=1;i<n;i++){
                if(n%i==0){
                    t++;
                    count[t] = i;//把i保存到数组
                    tran = tran-i;
                }
        }
        if(tran==0){
            cout<<n<<"是一个完数"<<endl;
            cout<<"质因子为 : ";
            for(int j=0;j<t;j++){
                cout<<count[j]<<",";
            }
            cout<<count[t]<<endl;
        }

    }
    return 0;
}
运行结果为:

你可能感兴趣的:(编程,C++)