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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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
Updated on 19-Dec-2019 09:58:48