Given a natural number n, the task is to print a pattern where each line shows the summation of the first k natural numbers (for all k from 1 to n) along with the total of those values. For Example:
Input: n = 5
Output:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
Let’s explore different methods to generate this summation pattern.
Using Mathematical Formula
The sum of first j natural numbers is computed using the direct formula j * (j + 1) // 2, and the expression string is built using join().
n = 5
for j in range(1, n + 1):
expr = " + ".join(str(i) for i in range(1, j + 1))
total = j * (j + 1) // 2
print(expr, "=", total)
Output
1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
Explanation:
- " + ".join(str(i) for i in range(1, j + 1)) builds the expression from 1 to j.
- j * (j + 1) // 2 uses the mathematical formula to compute the total.
Using Running Sum
A cumulative variable is updated by adding the current number j on each iteration, and the summation expression is formed using join().
n = 5
s = 0
for j in range(1, n + 1):
s += j
expr = " + ".join(str(i) for i in range(1, j + 1))
print(expr, "=", s)
Output
1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
Explanation:
- s += j updates the cumulative total for each line.
- join() creates the summation pattern string.
Using sum()
The numbers up to j are generated using range(), converted into a list, and summed using sum() while the expression is built using join().
n = 5
for j in range(1, n + 1):
nums = list(range(1, j + 1))
expr = " + ".join(str(i) for i in nums)
print(expr, "=", sum(nums))
Output
1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
Explanation:
- list(range(1, j + 1)) creates numbers needed for each line.
- sum(nums) computes the total.
- join() builds the final printed expression.
Using Iterative Printing
Numbers are printed one by one along with "+" when needed, while each value is stored inside a list and later summed.
n = 5
for j in range(1, n + 1):
a = []
for i in range(1, j + 1):
print(i, end=" ")
if i < j:
print("+", end=" ")
a.append(i)
print("=", sum(a))
Output
1 = 1 1 + 2 = 3 1 + 2 + 3 = 6 1 + 2 + 3 + 4 = 10 1 + 2 + 3 + 4 + 5 = 15
Explanation:
- print(i, end=" ") prints each number.
- The condition if i < j: prints "+" between terms.
- sum(a) calculates the total of the collected numbers.