在 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

更新於: 2019-12-19

99 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.