Find reminder of array multiplication divided by n in C++


Suppose we have an array of n elements called A. We have to print the remainder after multiply all the numbers divided by n. Suppose A = [100, 10, 5, 25, 35, 14], and n = 11. The output is 9. So the value of 100 * 10 * 5 * 25 * 35 * 14 mod 11 = 9.

First, we have to take the remainder of each number, then multiply the remainder with the current result. After multiplication, again take the remainder to avoid overflow.

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int getRemainder(int a[], int size, int n) {
   int mul = 1;
   for(int i = 0; i<size; i++){
      mul = (mul * (a[i] % n)) %n;
   }
   return mul%n;
}
int main() {
   int arr[] = {100, 10, 5, 25, 35, 14};
   int size = sizeof(arr)/sizeof(arr[0]);
   int n = 11;
   cout << "The remainder is: " << getRemainder(arr, size, n);
}

Output

The remainder is: 9

Updated on: 19-Dec-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements