
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements