Question
- You've to check whether a given number is prime or not.
- Take a number "t" as input representing count of input numbers to be tested.
- Take a number "n" as input "t" number of times.
- For each input value of n, print "prime" if the number is prime and "not prime" otherwise.
Input Format A number t A number n A number n .. t number of times
Output Format prime not prime not prime .. t number of times
Constraints 1 <= t <= 10000 2 <= n < 10^9
Sample Input 5 19 21 33 37 121
Sample Output prime not prime not prime prime not prime
What am I doing wrong? The program is takin inputs alright, but the result is varying again and again. The output is right for some inputs but wrong for some other? What am I missing??
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
boolean flag = true;
int t = scn.nextInt();
for (int i = 0; i < t; i++) {
int n = scn.nextInt();
for (int k = 2; k * k <= n; k++) {
if (n % k == 0) {
System.out.println("not prime");
flag = false;
break;
}
}
if (flag)
System.out.println("prime");
}
}
}