Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C/C++ Program to Find reminder of array multiplication divided by n ?
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 dividing 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 the modular arithmetic property: (a * b) % n = ((a % n) * (b % n)) % n.
Syntax
int multiplyRemainder(int arr[], int size, int n);
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
This example demonstrates how to find the remainder of array multiplication divided by n using modular arithmetic ā
#include <stdio.h>
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;
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Divisor (n): %d\n", n);
printf("Remainder: %d\n", multiplyRemainder(arr, size, n));
return 0;
}
Array elements: 12 35 69 74 165 54 Divisor (n): 47 Remainder: 14
How It Works
The algorithm uses the modular arithmetic property to prevent integer overflow. Instead of multiplying all elements first and then taking modulo, we apply modulo at each step:
- Step 1: Initialize mul = 1
- Step 2: For each array element, apply: mul = (mul * (arr[i] % n)) % n
- Step 3: This ensures the intermediate result never exceeds nā1
Conclusion
Using modular arithmetic prevents integer overflow when finding the remainder of large multiplications. This approach efficiently handles arrays of any size while maintaining accuracy and staying within integer limits.
