题解 | #完全数计算#【真因子的两个性质】
完全数计算
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;
}
}
海康威视公司福利 1382人发布
