Skip to content
Related Articles
Open in App
Not now

Related Articles

Python Program for Find remainder of array multiplication divided by n

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 14 Mar, 2023
Improve Article
Save Article
Like Article

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
Explanation: 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

Time Complexity: O(n), where n is the number of elements in the array. This is because the reduce function iterates through the entire array and performs the lambda function on each element.
Auxiliary Space: O(1), as the reduce function only requires a single variable to store the result.

Method2#: Without using inbuilt functions

Python3




arr = [100, 10, 5, 25, 35, 14];lens = len(arr);n = 11
mul = 1
for i in range(lens):
    mul = (mul * (arr[i] % n)) % n
print(mul % 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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!