在 C 陣列中尋找範圍的乘積
輸入引數陣列 L、R、P,任務是從 L 到 R 之間找到範圍的乘積(以模為輸出),然後顯示結果。
如下圖所示,我們有一個元素陣列,L 是作為 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
", calculateProduct(A, L, R, P));
return 0;
}輸出
24
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP