我不明白我做错了什么,没有语法错误,但它没有给出我想要的答案。该算法应该找到1到10000之间的整数,以获得最大数量的除数,并说明它包含多少除数。
public class pract3ex11 {
public static void main (String [] args) {
int n;
int i;
int c=0;
int max=0;
int result;
int d;
for (n=2; n<10000; n++){
d=c;
c=0;
int x=n;
result = x;
for (i=1; i<x; i++){
result= result%i;
if (result==0){
c++;
}
if (c>d){
max=n;
}
}
}
System.out.println(max+" "+c);
}
答案 0 :(得分:3)
设置max
时,您还应设置d
。否则,两者会失去同步:
if (c>d){
d = c;
max=n;
}
您还需要在循环之前将0
分配给d
,然后移除
d=c;
位于循环顶部。
答案 1 :(得分:0)
可能的解决方案:
public static void main(String[] args) {
int count;
int maxDivisors;
int number;
maxDivisors = 1;
number = 1;
for ( count = 2; count <= 10000; count ++ ) {
int x;
int divisors = 0;
for ( x = 1; x <= count; x++ ) {
if ( count % x == 0 )
divisors++;
}
if (divisors > maxDivisors) {
maxDivisors = divisors;
number = count;
}
}
System.out.println("The maximum number of divisors are " + maxDivisors);
System.out.println("Number is : " + number);
}