Python-courses-python-exercises-python-remainder-in-euclidean-division

Exercise 764

Write a python algorithm as function which takes as parameter an integer n and which returns the remainder in the Euclidean division by n of the sum of the first n integers Sn = 1 + 2 + 3 + ... + n.

Solution

# creating a function which calculates the sum of n first integer Sn = 1 + 2 + 3 + ... + n for a given integer n.
def sumFirst(n):
# Initializing the sum of first integer Sn = 1 + 2 + 3 + ... + n
s = 0

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

return s
# creating a function that calculate the remainder in the Euclidean division by n of the sum Sn = 1 + 2 + 3 + ... + n
def remainder_n(n):
# getting the sum Sn = 1 + 2 + 3 + ... + n
Sn = sumFirst(n)
# the searched remainder is
rm = Sn%n
return rm

# Testing algorithm for n = 24
print('The remainder in eucliean division of Sn by n is : ' , remainder_n(4)) # Sn = 1 + 2 + 3 + 4 = 10 , then Sn%4 = 2
# The output is : The remainder in eucliean division of Sn by n is : 2

Younes Derfoufi
my-courses.net

Leave a Reply