题解 | #完全数计算#【真因子的两个性质】

完全数计算

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int n = in.nextInt();
        int count = 0;

        while (n > 1) {
            if (isPerfect(n)) count ++;
            n--;
        }

        System.out.println(count);
    }

    static boolean isPerfect (int num) {
        int count = 1;
        // 假设真因子为 ab, a*b=m
        // 真因子的性质:
        // 1. 真因子成对出现在该数的平方根两边,即 a<=sqrt(m), b>=sqrt(m)
        // 推导法,if a>=sqrt(m) and a*b = m, then a*b>=sqrt(m)*b then m>=sqrt(m) * b then sqrt(m) >= b; 
        // 2. 真因子一定小于或等于 num/2,反证法
        // if a*b=m, a>m/2 then a*b>(m/2)*b then m>(m/2)*b then 2>b then b=1 then a=m 这个结论根条件相反,即 a=m,并不是 m 的真因子
        for (int i = 2; i <= num / i && i <= num / 2; i++) {
            if (num % i == 0) {
                count += i;
                count += (num / i);
            }
        }

        return count == num;
    }
}


全部评论

相关推荐

用微笑面对困难:只要你保证项目和获奖都是真的就行尤其是“对战,总负责人”啊这些套职,基本上队员,打杂的都这么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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