easyBasic Math Concepts
Check for Prime
Determine whether n is prime: it must be at least 2 and have exactly two positive divisors.
Work through the cases
3 examplesInput notation
An integer n from 0 through 1000000000.Expected result
true or false.Case 1
Input
29
Expected output
true
Case 2
Input
1
Expected output
false
Case 3
Input
2
Expected output
true
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
A composite number has a divisor no larger than its square root. Reject numbers below 2. Time: O(√n), extra space: O(1).
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Long> values = new ArrayList<>();
while (in.hasNextLong()) values.add(in.nextLong());
long[] a = values.stream().mapToLong(Long::longValue).toArray();
long n = a[0];
boolean prime = n >= 2; for (long i = 2; i <= n / i; i++) if (n % i == 0) { prime = false; break; } System.out.println(prime);
}
}
Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.