กำหนดด้วยอาร์เรย์ L, R, P เป็นอินพุต และภารกิจคือค้นหาช่วงระหว่าง L และ R กับผลิตภัณฑ์ภายใต้โมดูลัสเป็นเอาต์พุตและแสดงข้อมูลนั้น
ตามที่ให้ไว้ในรูป เรามีอาร์เรย์ขององค์ประกอบ และ L ซึ่งเป็นค่า Left เป็น 2 และ R ซึ่งเป็นค่าที่ถูกต้องเป็น 2 ตอนนี้โปรแกรมจะต้องค้นหาผลคูณของช่วงระหว่างกัน

ตัวอย่าง
Input-: A[] = { 1, 2, 3, 4, 5, 6 }
P = 29 L = 2 R = 6
Output-: 24
Input-: A[] = {1, 2, 3, 4, 5, 6},
L = 2 R = 5 P = 113
Output-: 7 แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
- รับอินพุตในอาร์เรย์ขององค์ประกอบจำนวนเต็ม, ค่าซ้าย(L), ค่าขวา(R) และ P(ค่าไพรม์)
- เริ่มการเคลื่อนที่ขององค์ประกอบจากค่าด้านซ้ายไปยังค่าด้านขวา
- เก็บการคูณไว้ในตัวแปรชั่วคราว
- ดำเนินการโมดูโลต่อไปด้วยค่าไพรม์
- พิมพ์ผลลัพธ์สุดท้าย
อัลกอริทึม
Start
Step 1 -> declare function to calculate product
int calculateProduct(int A[], int L,int R, int P)
declare variable as int i
set L = L – 1
set R = R – 1
declare int ans = 1
Loop For i = L and i <= R and i++
Set ans = ans * A[i]
Set ans = ans % P
End
return ans
Step 2-> In main()
Declare an array as int A[] = { 1, 2, 3, 4, 5, 6 }
Declare variable as int P = 29
Declare variable as int L = 2, R = 6
Print A, L, R, P
Stop ตัวอย่าง
#include <stdio.h>
int calculateProduct(int A[], int L,int R, int P) {
int i;
//Because array starts with 0 and
//L R starts from 1.
L = L - 1;
R = R - 1;
int ans = 1;
for ( i = L; i <= R; i++) {
ans = ans * A[i];
ans = ans % P;
}
return ans;
}
int main() {
int A[] = { 1, 2, 3, 4, 5, 6 };
int P = 29;
int L = 2, R = 6;
printf("%d\n", calculateProduct(A, L, R, P));
return 0;
} ผลลัพธ์
24