โจทย์: (a₁ × a₂ × ... × aₙ) mod m
คำนวณ modulo ทีละขั้นตอนป้องกัน overflow
คุณสมบัติ Modular Arithmetic
(a × b) mod m = ((a mod m) × (b mod m)) mod m
ตัวอย่างโค้ด
public class Demo {
public static int arrayProductMod(int[] arr, int m) {
long result = 1; // ใช้ long ป้องกัน overflow ระหว่างคูณ
for (int val : arr) {
result = (result * (val % m)) % m;
}
return (int) result;
}
public static void main(String[] args) {
int[] arr = {35, 100, 69, 99, 27, 88, 12, 25};
int m = 11;
System.out.println("Array: " + Arrays.toString(arr));
System.out.println("Modulo: " + m);
System.out.println("Result: " + arrayProductMod(arr, m));
// Verify
long full = 1;
for (int v : arr) full *= v;
System.out.println("Full product: " + full);
System.out.println("Full product % " + m + " = " + (full % m));
}
}
ผลลัพธ์
Array: [35, 100, 69, 99, 27, 88, 12, 25] Modulo: 11 Result: 0 Full product: 154679688000000 Full product % 11 = 0
จุดสำคัญ
- Mod ทีละขั้น:
result = (result * (val % m)) % m - ใช้
longสำหรับ intermediate result (int × int อาจ overflow) - ถ้า m ใหญ่ (ใกล้ Integer.MAX_VALUE) ใช้
BigIntegerหรือMath.multiplyExact - ถ้ามีค่า 0 ใน array → ผลลัพธ์เป็น 0 ทันที (short-circuit)
Java 8+ Stream Version
int result = Arrays.stream(arr)
.mapToLong(v -> v % m)
.reduce(1, (a, b) -> (a * b) % m)
.intValue();