题解 | #完全数计算#
完全数计算
https://www.nowcoder.com/practice/7299c12e6abb437c87ad3e712383ff84
来个大佬写下详细题解
通过HashMap记录之前计算过得数据 提高运行效率
通过HashMap记录之前计算过得数据 提高运行效率
再通过 质数的特点 除以2,且下次一定不会大于max的性质 减少计算量
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
while (in.hasNextInt()) {
int a = in.nextInt();
if(a < 6){
System.out.println(0);
break;
}
int count = 0;
for(int i = a; i >= 2; i--){
if(map.containsKey(i)){
map.put(a,map.getOrDefault(i,0)+count);
break;
}else{
if(isRes(i)) {
count++;
}
}
}
map.put(a,map.getOrDefault(a,count));
System.out.println(map.get(a));
}
}
// 判断是不是完美数
public static boolean isRes(int num ){
int sum = 1;
int max = num/2 +1;
for(int i = 2 ; i < max ; i ++){
if(num % i == 0 ){
sum += i;
sum += num/i;
max = num/i;
}
}
if(sum == num){
return true;
}else{
return false;
}
}
//
}
#牛客22届优选企业专场#