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
Selected Reading
Products of ranges in an array in C
The product of ranges in an array problem involves calculating the product of elements between given left (L) and right (R) indices under modulo P. This is useful in competitive programming to handle large products efficiently.
Syntax
int calculateProduct(int A[], int L, int R, int P);
Parameters
- A[] − The input array of integers
- L − Left index (1-based)
- R − Right index (1-based)
- P − Prime modulo value
Algorithm
Step 1: Convert 1-based indices to 0-based (L-1, R-1) Step 2: Initialize result as 1 Step 3: Iterate from L to R Step 4: Multiply each element with result Step 5: Apply modulo P to prevent overflow Step 6: Return final result
Example 1: Basic Range Product
Calculate product of elements from index 2 to 6 in array [1,2,3,4,5,6] −
#include <stdio.h>
int calculateProduct(int A[], int L, int R, int P) {
int i;
/* Convert 1-based indices to 0-based */
L = L - 1;
R = R - 1;
int ans = 1;
for (i = L; i <= R; i++) {
ans = ans * A[i];
ans = ans % P; /* Apply modulo to prevent overflow */
}
return ans;
}
int main() {
int A[] = {1, 2, 3, 4, 5, 6};
int P = 29;
int L = 2, R = 6;
printf("Array: [");
for (int i = 0; i < 6; i++) {
printf("%d", A[i]);
if (i < 5) printf(", ");
}
printf("]<br>");
printf("Range: L=%d to R=%d, Modulo P=%d<br>", L, R, P);
printf("Product: %d<br>", calculateProduct(A, L, R, P));
return 0;
}
Array: [1, 2, 3, 4, 5, 6] Range: L=2 to R=6, Modulo P=29 Product: 24
Example 2: Different Range and Modulo
Another example with different L, R, and P values −
#include <stdio.h>
int calculateProduct(int A[], int L, int R, int P) {
L = L - 1;
R = R - 1;
int ans = 1;
for (int i = L; i <= R; i++) {
ans = (ans * A[i]) % P;
}
return ans;
}
int main() {
int A[] = {1, 2, 3, 4, 5, 6};
int P = 113;
int L = 2, R = 5;
printf("Elements from index %d to %d: ", L, R);
for (int i = L-1; i <= R-1; i++) {
printf("%d ", A[i]);
}
printf("\nProduct under modulo %d: %d<br>", P, calculateProduct(A, L, R, P));
return 0;
}
Elements from index 2 to 5: 2 3 4 5 Product under modulo 113: 7
Key Points
- The function uses 1-based indexing for L and R, converting to 0-based internally
- Modulo operation is applied at each step to prevent integer overflow
- Time complexity is O(R-L+1) for the range calculation
- Space complexity is O(1) as only a few variables are used
Conclusion
Range product with modulo is an efficient way to calculate products of array segments while avoiding overflow. The key is applying modulo at each multiplication step and handling 1-based to 0-based index conversion properly.
Advertisements
