-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Solution.java
32 lines (29 loc) · 970 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// github.com/RodneyShag
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
while (T-- > 0) {
int n = scan.nextInt();
System.out.println(isPrime(n) ? "Prime" : "Not prime");
}
scan.close();
}
private static boolean isPrime(int n) {
if (n < 2) {
return false;
} else if (n == 2) { // account for even numbers now, so that we can do i+=2 in loop below
return true;
} else if (n % 2 == 0) { // account for even numbers now, so that we can do i+=2 in loop below
return false;
}
int sqrt = (int) Math.sqrt(n);
for (int i = 3; i <= sqrt; i += 2) { // skips even numbers for faster results
if (n % i == 0) {
return false;
}
}
return true;
}
}