DSA Factory
Free lessonsProgramming basics · Stage 5 · Functions · Step 3

Breaking a job into small jobs

Split a big task into helper functions that each answer one question. About 10 minutes.

Ask one small question

How would you count the prime numbers up to 20? You'd go through the numbers one at a time, and for each one ask: is this a prime? If yes, count it.

That's two jobs: walking through the numbers, and answering the question about one number. Keep them apart. Write the question as its own function, which returns true or false. A function that answers a yes-or-no question gets a name that sounds like a question, such as is_prime.

One job per function, with a name that says what it answers.

The helper, and the loop that uses it

A prime is a number bigger than 1 with no divisors except 1 and itself. To check, try every number from 2 up to just below it. If any of them divides it evenly, it is not a prime, so return false at once. If none do, return true.

Now the counting loop becomes easy to read: for each number, if it is prime, add one. You can test the helper alone, and then trust it inside the loop.

Test the small helper first, then use it in the bigger one.
In code
def is_prime(k):
    if k < 2:
        return False
    for d in range(2, k):
        if k % d == 0:
            return False
    return True
Counting primes up to 10
2
0
3
1
4
2
5
3
6
4
7
5
8
6
9
7
10
8
k
k
2
count
1

Ask the helper about 2. Nothing between 2 and 2 can divide it, so it is a prime. The count is 1.

Move 1 of 6
Quick check

How many prime numbers are there from 1 up to 10?

  1. A4
  2. B5
  3. C3
Show the answer

4. They are 2, 3, 5 and 7.

Your problem

Count the primes

Return how many prime numbers there are from 1 up to n. A prime is a number bigger than 1 whose only divisors are 1 and itself. Write a helper function that checks one number.

Example
n = 10 → 4

0 ≤ n ≤ 5,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding