Sum of Integers from 1 to n
In this lesson, we will learn how to find the sum of numbers from 1 to n.
We'll cover the following
What does the sum of integers from 1 to mean?
Natural numbers are positive numbers starting from . These can be written as:
We want to write a program that takes a number and sums up all the numbers from up till that number.
For example, if , then the sum of numbers from to is: .
Mathematical Notation
The sum of all numbers up to a number is equal to the sum of that number and the sum of all the numbers before it. Let’s write it down mathematically:
.
.
.
Generic Mathematical Notation
.
.
.
Implementation
def sumTill(targetNumber) :# Base Caseif targetNumber == 1 :return targetNumber# Recursive Caseelse :return targetNumber + sumTill(targetNumber - 1)# Driver CodetargetNumber = 5print(sumTill(targetNumber))
Explanation
Let’s begin by breaking down the solution into subtasks:
.
.
The last statement where execution halts, will now become our base case and the rest will be mapped to recursive case:
Let’s have a look at an another example in the next lesson.