โจทย์: กำหนดอาร์เรย์ตัวเลขและตัวหาร n หาเศษจากการคูณทุกตัวในอาร์เรย์แล้วหาร n
ใช้คุณสมบัติ modular arithmetic: (a × b) % c = ((a % c) × (b % c)) % c
คำนวณทีละตัว: หา modulo ของแต่ละตัว คูณสะสม แล้ว modulo อีกครั้ง ป้องกัน overflow
โค้ดตัวอย่าง
def findremainder(arr, lens, n):
mul = 1
for i in range(lens):
mul = (mul * (arr[i] % n)) % n
return mul % n
arr = [100, 1, 2, 3, 4, 5, 6, 6, 7]
lens = len(arr)
n = 11
print(findremainder(arr, lens, n))
ผลลัพธ์
1

สรุป
เรียนรู้วิธีหาเศษของผลคูณอาร์เรย์หาร n: ใช้ distributive property ของ modulo คูณทีละตัว modulo ทีละขั้น