Perfect number
Title description: For a positive integer, if it is equal to the sum of all positive factors except itself, we call it a "perfect number".
Given an integer n, if it is a perfect number, return true, otherwise return false.
Please refer to LeetCode official website for example description.
Source: LeetCode
Link: https://leetcode-cn.com/problems/perfect-number/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Solution one: Solution one
Add a Get NUM all positive factors (except itself) method calculateAllPrimeFactor , the return value is a List , returns the value of the sum of all the elements, it is judged whether or equal NUM , if equal, returns to true ; otherwise, return false .
The logic of as follows:
- First, declare a List to primeFactor ;
- If num is equal to 1, then directly return primeFactor ;
- Otherwise, add 1 to primeFactor ;
- If num less than 4, return primeFactor ;
- Traversing to and from the 2 NUM square root, if NUM be divisible thereof, this number and this number will be NUM added after the addition to the number primeFactor in.
- Finally return primeFactor .
import java.util.ArrayList;
import java.util.List;
/**
* @Author: ck
* @Date: 2021/10/3 11:43 上午
*/
public class LeetCode_507 {
public static boolean checkPerfectNumber(int num) {
List<Integer> primeFactor = calculateAllPrimeFactor(num);
for (Integer integer : primeFactor) {
num -= integer;
}
if (num == 0) {
return true;
}
return false;
}
public static List<Integer> calculateAllPrimeFactor(int num) {
List<Integer> primeFactor = new ArrayList<>();
if (num == 1) {
return primeFactor;
}
primeFactor.add(1);
if (num < 4) {
return primeFactor;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
primeFactor.add(i);
primeFactor.add(num / i);
}
}
return primeFactor;
}
public static void main(String[] args) {
System.out.println(checkPerfectNumber(28));
}
}
[Daily Message] Seize every minute and every second in reality, better than imagined one month and one year.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。