Perfect for

A positive integer is called a “perfect number” if it is equal to the sum of all positive factors except itself.

Given an integer n, return true if it is perfect, false otherwise.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/pe… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: Solution 1

Add a method calculateAllPrimeFactor to get all positive factors of num (except for itself), return a List, add all elements of the returned value to determine if they are equal to num, return true if they are equal; Otherwise, return false.

The logic of the calculateAllPrimeFactor method is as follows:

  • First, declare a List to be returned as primeFactor;
  • If num equals 1, return primeFactor directly;
  • Otherwise, add 1 to primeFactor;
  • If num is less than 4, return primeFactor;
  • It then iterates from 2 to the square root of num and, if num is divisible by it, adds that number and the number after that number is divided by num to the primeFactor.
  • Finally, return to 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)); }}Copy the code

Seize a moment in reality rather than a month and a year in imagination.