在 C++ 中求数组乘积除以 n 的余数
假设我们有一个包含 n 个元素的数组,称为 A。我们要打印乘以所有数字除以 n 后的余数。假设 A = [100, 10, 5, 25, 35, 14],且 n = 11。输出为 9。因此,100 * 10 * 5 * 25 * 35 * 14 mod 11 = 9。
首先,我们必须取每个数字的余数,然后将余数乘以当前结果。乘法完成后,再次取余数以避免溢出。
示例
#include<iostream>
#include<algorithm>
using namespace std;
int getRemainder(int a[], int size, int n) {
int mul = 1;
for(int i = 0; i<size; i++){
mul = (mul * (a[i] % n)) %n;
}
return mul%n;
}
int main() {
int arr[] = {100, 10, 5, 25, 35, 14};
int size = sizeof(arr)/sizeof(arr[0]);
int n = 11;
cout << "The remainder is: " << getRemainder(arr, size, n);
}输出
The remainder is: 9
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP