I'm a beginner programmer and I've just taken a challenge to find the greatest prime number of a very large number. But I've been trying to write a code to find a solution but I don't have any luck with it. This was my last attempt
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.
}
}
}
}
Several issues:
false
when you have a new value i;true
just because you found one value of j that is not a divisor of i. You should only do that when none of the values of j divide i. So this you can only decide on after having considered all values of j;Here is the suggested correction to your code:
Although this will work it is not optimal: you could stop looking for divisors j until the square root of i. And i should not have to increase further than the square root of num for the same reasons.