完美的数字查找器

时间:2016-10-07 01:47:25

标签: java

我的任务是创建一个完美的数字计算器,但我真的不明白如何去做。我在这里找到了一些例子,但显然不想复制,但我很难弄清楚每个部分的用途。

我知道第一个For循环意味着当min小于或等于10000时加1,但为什么下一个变量在循环内声明,以及为什么' e'是为了。是' e'应该是检查完美数字?

public static void main(String[] args){
    int min = 1; 
    int max = 10000;

    for (min = 1; min <= max; min++) { 
        int sum = 0;
        for (int e = 1; e < min; e++) {
            if ((min % e) == 0) {
                sum += e;
            } 
        }  
        if (sum == min){           
            System.out.println(sum);
        }          
    }      
} 

1 个答案:

答案 0 :(得分:2)

在数论中,perfect number是一个正整数,等于其正确的除数之和,即除数除数之外的正除数之和

让我们打破这段代码:

public static void main(String[] args){
// The lowest number we will check to see if it's perfect
int min = 1; 
// The highest number we will check to see if it's perfect
int max = 10000;

// A loop to go over all numbers in the range to check which of them are perfect
for (min = 1; min <= max; min++) { 
    // The sum of proper positive divisors for our number
    int sum = 0;
    // A loop to calculate the sum of positive divisors for our number, here 'e' will
    // go from 1 to 'min-1' (because a perfect number excludes the number itself)
    for (int e = 1; e < min; e++) {
        // This if is true if the number if a proper divisor of our number ('min')
        if ((min % e) == 0) {
            // The number is a proper divisor so we add it to the sum of proper divisors
            // for our number
            sum += e;
        } 
    }  
    // We finished checking all of our proper divisors for the number 'min'
    if (sum == min){           
        // If this is is true, that means that the sum of all proper divisors
        // for 'min' equals to 'min' -> 'min' is a perfect number, so we
        // print it
        System.out.println(sum);
    }          
}