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 false for numbers less than 2.
  • Only divisors up to the square root need to be checked.
  • Return true only when no divisor is found.

Example 1

Input
n (int) = 2
Returns (boolean) true

Example 2

Input
n (int) = 4
Returns (boolean) false

Example 3

Input
n (int) = 17
Returns (boolean) true

Example 4

Input
n (int) = 1
Returns (boolean) false

Example 5

Input
n (int) = 29
Returns (boolean) true

If 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

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.