Learner Level
Implement the method isPrime that checks whether an integer is prime.
Decide whether a number is prime. A prime number is greater than 1 and has no positive divisors except 1 and itself.
The task is designed to test careful handling of edge cases, not only the most common input.
- Return
falsefor numbers less than2. - Only divisors up to the square root need to be checked.
- Return
trueonly when no divisor is found.
Example 1
Input
n (int) =
2Returns (boolean)
trueExample 2
Input
n (int) =
4Returns (boolean)
falseExample 3
Input
n (int) =
17Returns (boolean)
trueExample 4
Input
n (int) =
1Returns (boolean)
falseExample 5
Input
n (int) =
29Returns (boolean)
trueIf a number has a large factor, it also has a matching smaller factor. Checking while i * i <= n is enough.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run