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.
for d in range(2, n + 1):
if n % d == 0:
return dThe 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.
- d
- 2
- n
- 35
Try d = 2. 35 divided by 2 leaves a remainder of 1, so it doesn't divide evenly. Move on.
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?
- AThe function ends at once, and d is the answer
- BThe loop carries on to the end, then returns d
- 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.
Smallest factor
Return the smallest whole number bigger than 1 that divides n evenly. For a prime number, that is n itself.
n = 35 → 5
2 ≤ n ≤ 1,000,000