题解 | #完全数计算#

完全数计算

https://www.nowcoder.com/practice/7299c12e6abb437c87ad3e712383ff84

// 优化一下:函数perfect里面的for循环只遍历到 n/2。
#include <iostream>
using namespace std;
bool perfect(int n){
    int sum = 0;
    for(int i = 1; i <= n/2; ++i){
        if(n % i == 0){
            sum += i;
        }
    }
    
    return n == sum;
}


int main() {
    int n;
    cin >> n;
    int cnt = 0;
    for(int i = 1; i <= n; ++i){
        if(perfect(i)){
            cnt++;
        }
    }

    cout << cnt << endl;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

挥毫自在:想白嫖你呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务