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

Answering early

Return from inside a loop the moment you know the answer. About 8 minutes.

Return ends everything

When return runs, the function is over. Everything after it, including the rest of any loop, never happens. That is handy when you're searching for something.

Say you want the first number that fits a rule. Walk through the numbers one by one. The moment you find one that fits, return it. There's no point checking the rest. A function that stops early is also quicker, because it does less work.

return inside a loop: ends the loop and the function together.
In code
for d in range(2, n + 1):
    if n % d == 0:
        return d

The smallest factor

A factor of n is a number that divides it evenly. The smallest factor of 35, apart from 1, is 5, because 2, 3 and 4 don't fit. Try d = 2, 3, 4 and so on. The first d that divides n evenly is the answer.

You are sure to find something, because n divides itself. So for a prime number like 7, the loop will reach 7 and return 7. No line is needed after the loop, but some languages want one anyway.

Return at the first match, not at the last one.
The smallest factor of 35
2
0
3
1
4
2
5
3
6
4
7
5
d
d
2
n
35

Try d = 2. 35 divided by 2 leaves a remainder of 1, so it doesn't divide evenly. Move on.

Move 1 of 5
Quick check

A function loops over the numbers 2, 3, 4, and so on, and has the line: if n % d == 0, return d. What happens as soon as that return runs?

  1. AThe function ends at once, and d is the answer
  2. BThe loop carries on to the end, then returns d
  3. CThe loop carries on and may return again
Show the answer

The function ends at once, and d is the answer. return finishes the whole function immediately, loop and all.

Your problem

Smallest factor

Return the smallest whole number bigger than 1 that divides n evenly. For a prime number, that is n itself.

Example
n = 35 → 5

2 ≤ n ≤ 1,000,000

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