在 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