Here's one possible implementation:

public static boolean isPerfect(int n) { return properFactorSum(n) == n; }

public static int properFactorSum(int n) { return properFactorSum(1, n); }

public static int properFactorSum(int k, int n) { if (n == 1) { return 0; } if (k > n / 2) { return 0; } if (n % k == 0) { return k + properFactorSum(k + 1, n); } return properFactorSum(k + 1, n); }

The isPerfect method simply checks if the sum of proper factors of n is equal to n.

The properFactorSum method is recursive and calculates the sum of proper factors of n. It does this by starting with k=1 (the first possible factor) and checking if k is a factor of n. If it is, then k is added to the sum and the method is called recursively with k+1 and n. If k is not a factor of n, the method is called recursively with k+1 and n. The base cases are when n=1 (the sum is 0) and when k is greater than n/2 (there are no more factors to check).

Note that this implementation assumes that n is positive and less than 10000, and it does not handle any errors or exceptions.


原文地址: http://www.cveoy.top/t/topic/bO7A 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录