题解 | #完全数计算# java模块设计 便于讨论
完全数计算
https://www.nowcoder.com/practice/7299c12e6abb437c87ad3e712383ff84
// package hj; // 完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。 import java.util.*; // 它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。 // 例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。 // 输入n,请输出n以内(含n)完全数的个数。 public class Main { public static void main(String[] args) { int count = 0; Scanner sc = new Scanner(System.in); int input = sc.nextInt(); for (int i = 1; i < input; i++) { if (valid(i)) { count++; } } System.out.println(count); sc.close(); } @Deprecated public static int[] find_factor(int n) { int[] res = new int[] {0}; // int[] ans = new int[]{1,2,3}; int count = 0; for (int i = 1; i <= n / 2 ; i++) { if (n % i == 0) { res[count] = i; count++; } } return res; }//弃用的函数 public static List<Integer> isPerfect(int n) { List<Integer> res = new ArrayList<Integer>(); for (int i = 1; i <= n / 2; i++) { if (n % i == 0) { res.add(i); } } return res; } public static boolean valid(int n) { int sum = 0; for (Integer num : isPerfect(n)) { sum += num; } if (sum == n) { return true; } return false; } }