하나의 수가 완전수나 완전 제곱수인지 아닌지를 판단하다

package com.thinkgem.jeesite.test;

import com.google.common.collect.Sets;

import java.util.Scanner;
import java.util.Set;

/**
 * @Description:
 * @Author: leo.xiong
 * @CreateDate: 2020/05/06 09:12
 * @Email: [email protected]
 * @Version:
 */
public class PerfectNumberTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String goBack = "NO";
        do {
            System.out.println(" ");
            Integer num = scanner.nextInt();
            Boolean isPerfectNumber = isPerfectNumber(num);
            if (isPerfectNumber) {
                System.out.println("【" + num + "】 ");
            }
            Boolean isPerfectSquareNumber = isPerfectSquareNumber(num);
            if (isPerfectSquareNumber) {
                System.out.println("【" + num + "】 ");
            }
            System.out.println(" :YES OR NO");
            goBack = scanner.next();
        } while (!"YES".equalsIgnoreCase(goBack));

    }

    /**
     *  
     *   , 1,   :6=1+2+3
     *
     * @param num
     * @return
     */
    public static Boolean isPerfectNumber(Integer num) {
        if (num <= 2) {
            return false;
        }
        Set allApproximateNumberSet = Sets.newHashSet();
        allApproximateNumberSet.add(1);
        for (int i = 2; i < num; i++) {
            Integer value = getApproximateNumber(i, num);
            if (value != null) {
                allApproximateNumberSet.add(i);
                allApproximateNumberSet.add(value);
            }
        }
        Integer sumValue = 0;
        for (Integer value : allApproximateNumberSet) {
            sumValue += value;
        }
        return sumValue.intValue() == num.intValue();
    }

    /**
     *  
     *  0 1  9=3*3
     *
     * @param num
     * @return
     */
    public static Boolean isPerfectSquareNumber(Integer num) {
        if (num == 0 || num == 1) {
            System.out.println("【" + num + "】 ");
            return true;
        }
        Boolean isPerfectSquareNumberFlag = false;
        for (int i = 2; i < num; i++) {
            if (!isPerfectSquareNumberFlag) {
                isPerfectSquareNumberFlag = (i * i == num);
                if (isPerfectSquareNumberFlag) {
                    return true;
                }
            }
        }
        return false;
    }

    public static Integer getApproximateNumber(int i, Integer num) {
        Double value = num.doubleValue() / i;
        if (value.intValue() == value) {
            return value.intValue();
        }
        return null;
    }
}

좋은 웹페이지 즐겨찾기