Learner Level

Implement the isPrimeNumber method that checks whether the given number is prime.

The input contains an integer n. Your task is to check whether n is a prime number.

A prime number is greater than 1 and has exactly two factors: 1 and itself. For example, 7 is prime, but 10 is not because it is divisible by 2 and 5.

Example 1

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

Example 2

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

Example 3

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

First reject numbers less than or equal to 1, because they are not prime.

For larger numbers, test possible divisors from 2 up to the square root of n. If any divisor divides n exactly, the number is not prime. If no divisor is found, the number is prime.

Pseudocode:

function isPrimeNumber(n):
    if n <= 1:
        return false
    divisor = 2
    while divisor * divisor <= n:
        if n % divisor == 0:
            return false
        divisor++
    return true
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.