Exercise
For each natural number n, we set: Sn = 1 + 2 + 3 + ... + n. Write a Python algorithm that finds the integer n for a given Sn. Example if Sn = 10 then n = 4 since 1 + 2 + 3 + 4 = 10.
Solution
def backSum(Sn):
# Initializing value of n
n = 1
i = 0
while ( n < Sn):
i = i + 1
n = n + i
return i
# Testing algorithm for Sn = 10 = 1+2+3+4. The algorothm must be return 4
print(backSum(10))
Younes Derfoufi
my-courses.net
my-courses.net