java初学者中不寻常的棘手情况

时间:2015-07-19 14:55:05

标签: java

此程序用于查找最大除数在1到10000之间的数字。无论两个数字是否有最大值,我们只打印一个。

int integerWithMax =1; // first, 1 as integer with max divisor
int maxDivisor = 1;   // 1 has max divisor
for (int i = 2; i <= 10000; i++) {
    int j;
    int divisorCount = 0;
    for (j = 1; j < i; j++) {
        if((i % j) == 0) {
            divisorCount++;
        }
    }
    if (divisorCount > maxDivisor) {
        // maxDivisor = divisorCount; //why do I need this line if I need only integerWithMax 
        integerWithMax = i;
    }
}
System.out.print("The integer with max divisor is "+integerWithMax );

问题在于,如果我取消注释maxDivisor,它会使用maxDivisor = 7560给出正确的整数,但如果我发表评论,integerWithMax将输出10000

问题是,如果我必须找到具有最大除数的整数,即maxDivisor,我应该分配给integerWithMax

1 个答案:

答案 0 :(得分:0)

此代码查找具有最高除数的1到10000之间的数字。我已对代码进行了评论,以便您了解正在发生的事情。

int integerWithMax = 1; // say that 1 is the integer with most divisors
int maxDivisor = 1;   // 1 has only a single divisor, itself

for (int i = 2; i <= 10000; i++) { // test each integer 2-10000
    int j;
    int divisorCount = 0;     // keep track of the number of divisors for integer i
    for (j = 1; j < i; j++) { // for each number smaller than i
        if((i % j) == 0) {    // if j is a divisor
            divisorCount++;   // increment the count of divisors
        }
    }
    // if my integer has a higher number of divisors than have previously been seen
    if (divisorCount > maxDivisor) {
        maxDivisor = divisorCount; // keep track of the new highest number of divisors
        integerWithMax = i;        // keep track of the integer
    }
}
System.out.print("The integer with max divisor is "+integerWithMax );

如果你注释掉maxDivisor = divisorCount;,那么if语句总是在问“这个整数是否有多个除数?”,对于所有非素数的数字都是如此。