Intermediate Level

Implement the countPrimeNumbersUpToN method that counts all prime numbers from 2 up to the given number.

The input contains an integer n. Your task is to count how many prime numbers are present from 2 up to n, including n if it is prime.

For example, when n = 10, the prime numbers are 2, 3, 5, and 7, so the answer is 4.

Example 1

Input
n (int) = 10
Returns (int) 4

Example 2

Input
n (int) = 20
Returns (int) 8

Example 3

Input
n (int) = 1
Returns (int) 0

Check each number from 2 to n and count it only if it is prime.

To test whether a number is prime, try dividing it by values from 2 up to its square root. If none of those values divide it exactly, it is prime.

Pseudocode:

function countPrimeNumbersUpToN(n):
    count = 0
    for number from 2 to n:
        if isPrime(number):
            count++
    return count
function isPrime(number):
    if number <= 1:
        return false
    divisor = 2
    while divisor * divisor <= number:
        if number % 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.