Python Program for Find remainder of array multiplication divided by n
Write a Python program for a 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
Input : arr[] = {100, 10},
n = 5
Output : 0
Explanation: 100 x 10 = 1000 % 5 = 0
Python Program to Find remainder of array multiplication divided by n using Naive approach:
First multiple all the number then take % by n then find the remainder, But in this approach, if the number is maximum of 2^64 then it give the wrong answer.
Below is the implementation of the above approach:
Python3
def findremainder(arr, len , n):
product = 1
for i in range ( len ):
product = product * arr[i]
return product % n
arr = [ 100 , 10 , 5 , 25 , 35 , 14 ]
len = len (arr)
n = 11
print (findremainder(arr, len , n))
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach that avoids overflow :
First take a remainder or individual number like arr[i] % n. Then multiply the remainder with current result. After multiplication, again take remainder to avoid overflow. This works because of distributive properties of modular arithmetic. ( a * b) % c = ( ( a % c ) * ( b % c ) ) % c
Below is the implementation of the above approach:
Python3
def findremainder(arr, lens, n):
mul = 1
for i in range (lens):
mul = (mul * (arr[i] % n)) % n
return mul % n
arr = [ 100 , 10 , 5 , 25 , 35 , 14 ]
lens = len (arr)
n = 11
print ( findremainder(arr, lens, n))
|
Time Complexity: O(len), where len is the size of the given array
Auxiliary Space: O(1)
Approach by using the functools.reduce method
We have used the reduce function from the functools module to iteratively multiply all elements in the input array and calculate the remainder after each multiplication operation when divided by the given number n.
Below is implementation for the above approach:
Python3
from functools import reduce
def remainderAfterMultiplication(arr, n):
result = reduce ( lambda x, y: (x * y) % n, arr)
return result
arr1 = [ 100 , 10 , 5 , 25 , 35 , 14 ]
n1 = 11
result1 = remainderAfterMultiplication(arr1, n1)
print (result1)
arr2 = [ 100 , 10 ]
n2 = 5
result2 = remainderAfterMultiplication(arr2, n2)
print (result2)
|
Time Complexity: O(len), where len is the size of the given array
Auxiliary Space: O(1)
Please refer complete article on Find remainder of array multiplication divided by n for more details!
Last Updated :
04 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...