- #include <iostream>
- #include<cmath>
- using namespace std;
- int main( )
- {
- int i,s,j;
- cout<<"2-1000之间的完数有:";
- for(i=2;i<=1000;i++)
- {
- s=1; //1是任何数的因子,所以不再s=1,也使下一句可以从2开始
- for(j=2;j<sqrt(i);j++) //正因为j从2开始,才让j到sqrt(i)
- if(i%j==0) s+=(j+i/j); //加上j的同时,和j对称的那个因子(i/j)也被累加了
- //思考:如果j允许从1开始,上式会将i本身也累加上去
- if(i==s) cout<<i<<" ";
- }
- cout<<endl;
- return 0;
- }
下面的程序也可以求解,考虑了效率,但不够彻底。
- #include <iostream>
- using namespace std;
- int main( )
- {
- int i,s,j;
- cout<<"2-1000之间的完数有:";
- for(i=2;i<=1000;i++)
- {
- s=1;
- for(j=2;j<=i/2;j++)
- if(i%j==0) s+=j;
- if(i==s) cout<<i<<" ";
- }
- cout<<endl;
- return 0;
- }