The Student Room Group

Java coding help

my program is intended to check if a number inputted by the user is prime, unfortunately the '!isPrime' part if the while loop doesnt stop the while loop if it finds a factor of the number inputted, and it just carries on.. would love if anyone could tell me why it isnt working . thanks


class Prime{
public static void main(String args[]){

long n;
boolean isPrime=false;
MaInput Ma = new MaInput();
int i=2;

n=Ma.readLong("Input a number, please!");
while(!isPrime||i<n){
if(n%i==0){
isPrime=false;
System.out.println(n+" is not prime");
}
else{
isPrime=true;
System.out.println(n+" is prime");
}
i++;
}
}
}
Original post by georgec123
my program is intended to check if a number inputted by the user is prime, unfortunately the '!isPrime' part if the while loop doesnt stop the while loop if it finds a factor of the number inputted, and it just carries on.. would love if anyone could tell me why it isnt working . thanks

while(!isPrime||i<n){

Shouldn't this be &&, not ||? Otherwise the statement will always be true if i<n.

edit: No, I don't know what you're doing.
(edited 8 years ago)
Original post by georgec123
my program is intended to check if a number inputted by the user is prime, unfortunately the '!isPrime' part if the while loop doesnt stop the while loop if it finds a factor of the number inputted, and it just carries on.. would love if anyone could tell me why it isnt working . thanks


class Prime{
public static void main(String args[]){

long n;
boolean isPrime=false;
MaInput Ma = new MaInput();
int i=2;

n=Ma.readLong("Input a number, please!":wink:;
while(!isPrime||i<n){
if(n%i==0){
isPrime=false;
System.out.println(n+" is not prime":wink:;
}
else{
isPrime=true;
System.out.println(n+" is prime":wink:;
}
i++;
}
}
}


Your program just finds factors of the input

it should be

int i = 2;
while (i < n) {
if (n % i == 0) { isPrime = true; break; }
else {i++;}
}

Quick Reply

Latest