C/C++ Program to Find reminder of array multiplication divided by n ?

CServer Side ProgrammingProgrammingC++

Here we will see how to calculate the remainder of array multiplication after dividing the result by n. The array and the value of n are supplied by the user. Suppose the array is like {12, 35, 69, 74, 165, 54} so the multiplication will be (12 * 35 * 69 * 74 * 165 * 54) = 19107673200. Now if we want to get the remainder after diving this by 47 it will be 14.

As we can see this problem is very simple. we can easily multiply the elements then by using modulus operator, it can get the result. But the main problem is when we calculate the multiplication, it may exceed the range of integer, or long also. So it may return some invalid results. To overcome this problem, we will follow this process.

Algorithm

multiplyRemainder(arr, size, n)

begin
   mul := 1
   for i in range 0 to size – 1, do
      mul := (mul * (arr[i] mod n)) mod n
   done
   return mul mod n
end

Example

 Live Demo

#include<iostream>
using namespace std;
int multiplyRemainder(int arr[], int size, int n){
   int mul = 1;
   for(int i = 0; i<size; i++){
      mul = (mul * (arr[i] % n)) % n;
   }
   return mul % n;
}
int main(){
   int arr[6] = {12, 35, 69, 74, 165, 54};
   int size = 6;
   int n = 47;
   cout << "Remainder: " << multiplyRemainder(arr, size, n);
}

Output

Remainder: 14
raja
Published on 26-Jul-2019 11:31:53
Advertisements