0

Hello friends can you guys tell me what’s wrong with my code in both side it will print this is prime number thank u

public class Program { public static void main(String[] args) { int Number=7; int x=0; for(int i=2; i<=-1;i++) { if(Number%i==0) x=x+1; } if(x>0){ System.out.println("The number is not prime"); } else{ System.out.println("The number is Prime"); } } }

20th May 2019, 6:10 AM
Sam
Sam - avatar
1 Resposta
0
Well, in the for loop you wrote in the condition i <= -1, instead of i <= Number - 1; and that kind of never executes the loop so x stays 0 and it will print that its a prime. Also, the code is not perfect, because this will register 1 as a prime number, which isn't. You should do it like this: for (int i = 1; i <= Number; i++) { if (Number % i == 0) x++; } if (x == 2) { System.out.println("Prime"); } else if (x == 1) { System.out.println("1"); } else if (x == 0) { System.out.println("Negative number"); } else { System.out.println("Not Prime"); }
20th May 2019, 6:28 AM
Airree
Airree - avatar