我是一名初学程序员,我刚刚接受挑战,找到了一个非常大的数字的最大素数。但我一直试图编写代码来寻找解决方案,但我没有运气。这是我的最后一次尝试
public class primeNums {
public static void main(String [] args) {
int num = 100000;
int rem = 0;
int prime = 0;
boolean isPrime = true;
int j = 2;
for(int i = 1;i < num;++i) { //Outer loop to find the factor of the num.
rem = num % i;
if((rem == 0)&&(i != 1)) { //Checking if i is a factor.
while((j <= i) && (isPrime)) { //Inner loop trying to find if i is prime.
if((i % j) == 0) { //Checking if i/j has any remainders.
isPrime = false; //If there isn't any remainders, i isn't
//prime, isPrime, is false and exists the
//inner loop.
}
else { //If i/j has any remainders, continue the
//loop and print the value of i (a test).
isPrime = true;
System.out.println(i);
}
++j; //Increment j until inner loop condition
} //becomes false.
}
}
}
}
答案 0 :(得分:1)
几个问题:
false
; true
,因为您发现 j 的一个值不是 i 的除数。只有在 j 的值 none 除以 i 时才应该这样做。因此,您只能在考虑了 j ; 以下是对代码的建议更正:
int num = 100000;
int factor = 0;
int rem = 0;
int prime = 0;
boolean isPrime = true;
int j = 2;
for(int i = 1;i < num;++i) {
rem = num % i;
if((rem == 0)&&(i != 1)) {
j = 2; // set j back to start
isPrime = true; // assume prime before iterating
while(j < i && isPrime) { // don't let j become equal to i
if((i % j) == 0) {
isPrime = false;
} // don't set isPrime to true until you have completed all iterations
++j;
}
if (isPrime) { // now is the time to check!
prime = i; // remember this prime
}
}
}
// output result
System.out.println("largest prime divisor: " + prime);
虽然这样可行但却不是最佳:你可以停止寻找除数 j ,直到 i 的平方根。由于同样的原因, i 不应该比 num 的平方根增加更多。