คูณสมาชิกทุกตัวใน Array แล้วหาเศษจากการหารด้วย n ตัวอย่าง:
Input: arr[] = {12, 35, 69, 74, 165, 54}; N = 47 Output: 14คำอธิบาย
ผลคูณ = 12*35*69*74*165*54 = 19107673200 หาร 47 เศษ 14
วิธีง่าย: คูณหมดแล้ว Mod แต่ถ้าผลคูณเกิน 2^64 จะผิด วิธีดีกว่า: Mod ทีละตัวระหว่างคูณ (Modular Arithmetic)
ตัวอย่าง
#include <stdio.h>
int main() {
int arr[] = {12, 35, 69, 74, 165, 54};
int len = 6;
int n = 47;
int mul = 1;
for (int i = 0; i < len; i++)
mul = (mul * (arr[i] % n)) % n;
printf("the remainder is %d", (mul % n));
return 0;
}ผลลัพธ์
the remainder is 14