Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมคำนวณราคาสินค้าหลังผ่านไป n วัน (Modular Exponentiation) ใน Python

โจทย์

ราคาสินค้าเริ่มต้น x ทุกวันราคาเพิ่มเป็น x เท่าของวันก่อน หาราคาหลัง y วัน (Mod 1e9+7) Input เป็น List of Pairs (x, y)

ตัวอย่าง: (5,2)→25, (6,8)→1679616, (2,12)→4096 และตัวเลขใหญ่ Mod 1e9+7

อัลกอริธึม

ใช้ pow(x, y, 1000000007) (Modular Exponentiation แบบ Built-in)

โค้ด Python


def solve(nums):
    for i in range(len(nums)):
        x, y = nums[i][0], nums[i][1]
        print(pow(x, y, 1000000007))

solve([(5, 2), (6, 8), (2, 12),
       (2722764242812953792238894584, 3486705296791319646759756475),
       (1505449742164712795427942455727527, 61649494321438487460747056421546274264)])
# Output: 25, 1679616, 4096, 754504594, 32955023

Input / Output

Input:  List of (x, y) pairs
Output: 25 1679616 4096 754504594 32955023