在 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