完全数计算
参考:https://www.nowcoder.com/profile/1470346/codeBookDetail?submissionId=12557587
#include<iostream> using namespace std; bool is_Perfect_Num(int n) { int sum=0,j=1,t=n/2; while(j<t) { if(n%j==0) { sum+=j; if(j!=1) { t = n/j; if(j!=n/j) sum+=n/j; } } ++j; if(sum>n) return false; } return (sum==n)?true:false; } int count_Perfect_Num(int n) { if(n<=0||n>=500000) return -1; int cnt = 0; for(int i=1;i<=n;i++) { if(is_Perfect_Num(i))++cnt; } return cnt; } int main() { int num; while(cin>>num) { cout<<count_Perfect_Num(num)<<endl; } return 0; }
解法2:https://www.nowcoder.com/profile/7562989/codeBookDetail?submissionId=12524988
#include<iostream> #include<algorithm> using namespace std; int count(int n) { int cnt = 0; if ((n < 0) | (n>500000)) return -1; else { for (int i = 2; i <= n; i++) { int sum = 0; int sq = sqrt(i); for (int j = 2; j <= sq; j++) { if (i%j == 0) { if (i / j == j) sum += j; else sum += j + (i / j); } } if (sum + 1 == i) cnt++; } return cnt; } } int main() { int input; while(cin>>input) cout << count(input) << endl; return 0; }