Sum of numbers from 1 to n

suggest change

If I wanted to find out the sum of numbers from 1 to n where n is a natural number, I can do 1 + 2 + 3 + 4 + ... + (several hours later) + n. Alternatively, I could write a for loop:

n = 0
for i in range (1, n+1):
    n += i

Or I could use a technique known as recursion:

def recursion(n):
    if n == 1:
        return 1
    return n + recursion(n - 1)

Recursion has advantages over the above two methods. Recursion takes less time than writing out 1 + 2 + 3 for a sum from 1 to 3. For recursion(4), recursion can be used to work backwards:

Function calls: ( 4 -> 4 + 3 -> 4 + 3 + 2 -> 4 + 3 + 2 + 1 -> 10 )

Whereas the for loop is working strictly forwards: ( 1 -> 1 + 2 -> 1 + 2 + 3 -> 1 + 2 + 3 + 4 -> 10 ). Sometimes the recursive solution is simpler than the iterative solution. This is evident when implementing a reversal of a linked list.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents