isPrime Method
Completed
Write static boolean isPrime(int n). Read n numbers and print only the primes on one line.
Input
Line 1: n. Line 2: n integers.
Output
The primes on one line.
Example
Input
9 1 2 3 4 5 9 11 15 17
Output
2 3 5 11 17
Editor
Java
Hints
Return false as soon as you find a divisor.
Solution explanation
Methods let you name an idea (is prime) and reuse it.
Show solution
import java.util.Scanner;
public class Main {
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
if (isPrime(x)) {
sb.append(sb.length() > 0 ? " " : "").append(x);
}
}
System.out.println(sb);
}
}