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

โปรแกรม Python หาผลรวมอนุกรมที่พจน์ที่ n คือ n² - (n-1)²

โจทย์: กำหนด n หาผลรวมพจน์ที่ n โดย Tn = n² - (n-1)²

ใช้ modular multiplication เพื่อลดความซับซ้อน

โค้ดตัวอย่าง

mod = 1000000007
def findSum(n):
    return ((n % mod) * (n % mod)) % mod

n = 229137999
print(findSum(n))

ผลลัพธ์

218194447

โปรแกรม Python หาผลรวมอนุกรมที่พจน์ที่ n คือ n² - (n-1)²

สรุป

เรียนรู้วิธีหาผลรวมอนุกรม Tn = n² - (n-1)² ใน Python ใช้ modular arithmetic