Skip to content
Related Articles

Related Articles

Python Program for Find remainder of array multiplication divided by n

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 07 Jun, 2022

Given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n.
Examples: 

Input : arr[] = {100, 10, 5, 25, 35, 14}, n = 11
Output : 9
Explaination: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9

Naive approach: First multiple all the numbers then take % by n to find the remainder, But in this approach, if the number is a maximum of 2^64 then it gives the wrong answer.

An approach that avoids overflow: First take a remainder or individual number like arr[i] % n. Then multiply the remainder with the current result. After multiplication, again take the remainder to avoid overflow. This works because of the distributive properties of modular arithmetic. ( a * b) % c = ( ( a % c ) * ( b % c ) ) % c 

Python3




# to use reduce function import reduce from functools
from functools import reduce
 
 
def find_remainder(arr, n):
    sum_1 = reduce(lambda x, y: x*y, arr)
    remainder = sum_1 % n
    print(remainder)
 
 
arr = [100, 10, 5, 25, 35, 14]
n = 11
find_remainder(arr, n)

Output

9

Please refer complete article on Find remainder of array multiplication divided by n for more details! 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!