Find last k digits in product of an array numbers in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements called A. We have another number k. Our task is to find last k digits of the product of elements in the array A. Suppose the A = [15, 22, 13, 19, 17], then the product is 1385670, the last k = 3 digits are 670.

To solve this problem, we will multiply the numbers under modulo 10k.

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int displayLastKNumbers(int array[], int n, int k) {
   int mod = (int)pow(10, k);
   int mul = array[0] % mod;
   for (int i = 1; i < n; i++) {
      array[i] = array[i] % mod;
      mul = (array[i] * mul) % mod;
   }
   return mul;
}
int main() {
   int a[] = {15, 22, 13, 19, 17};
   int k = 3;
   int n = sizeof(a) / sizeof(a[0]);
   cout <<"Last K digits are: " << displayLastKNumbers(a, n, k);
}

Output

Last K digits are: 670
raja
Published on 19-Dec-2019 14:27:27
Advertisements