making a greatest prime factor finder, and the logic is good to go but for some reason the code after the while statement will not spit out and I can't figure out why.
public class LargestPrime {
public static int getLargestPrime(int number) {
if(number <=1){
return -1;
}
int largestPrime = 0;
int factor = 0;
int i =1;
while(i < number) {
i++;
factor = number % i;
if (factor == 0) {
int primeCheck = i;
System.out.println(i + " is a factor of " + number);
if(primeCheck % 2 == 0){
System.out.println(primeCheck + " is not a prime factor");
continue;
}
for(int j = 2; j < primeCheck; j++){
if(primeCheck % j == 0){
System.out.println(primeCheck + " is not a prime factor");
return -1;
}
}largestPrime = primeCheck;
System.out.println(primeCheck + " is a prime factor");
//largestPrime = primeCheck;
}
}
System.out.println("loop has ended");
System.out.println(largestPrime + " is the largest prime factor");
return largestPrime;
}
}
Console output is : 3 is a factor of 45 3 is a prime factor 5 is a factor of 45 5 is a prime factor 9 is a factor of 45 9 is not a prime factor
Process finished with exit code 0
for some reason after the while loop ends its not printing out the last println statements which should be printing out the largest prime factor. IntelliJ isn't throwing any flags saying that the code is unreachable and my loop should end when I = number. so I'm not sure what the issue is here I tried playing with the scope and that did not fix the issue any insight would be greatly appreciated.
for some reason after the while loop ends its not printing out the last println statements which should be printing out the largest prime factor. IntelliJ isn't throwing any flags saying that the code is unreachable and my loop should end when I = number. so I'm not sure what the issue is here I tried playing with the scope and that did not fix the issue any insight would be greatly appreciated. I'm really trying to wrap my brain around why the last three lines are not executing and I can't find the issue.
When you find that
primeCheckis not prime, you should check the nextiinstead of returning.And since
2is a prime number, theprimeCheck % 2 == 0check is unnecessary.and
output: