วิเคราะห์อนุกรม
พจน์ที่ n: T(n) = n² - (n-1)² = n² - (n² - 2n + 1) = 2n - 1
ผลรวม n พจน์แรก: S(n) = Σ(2i - 1) = 2Σi - Σ1 = 2(n(n+1)/2) - n = n²
สรุป: ผลรวม = n²
ตัวอย่างโค้ด (ใช้สูตรตรง - O(1))
public class Demo {
// คำนวณ n² mod 1000000007
static final long MOD = 1_000_000_007L;
public static long computeSum(long n) {
n %= MOD;
return (n * n) % MOD;
}
public static void main(String[] args) {
long n = 45687234;
System.out.println("Sum of series (n^2) mod 1e9+7: " + computeSum(n));
}
}
ผลลัพธ์
Sum of series (n^2) mod 1e9+7: 335959495
คำอธิบาย: อนุกรม n² - (n-1)² ทำให้เกิด telescoping series ผลรวม = n² ใช้ modular arithmetic ป้องกัน overflow
การพิสูจน์ Telescoping
S(n) = [1² - 0²] + [2² - 1²] + [3² - 2²] + ... + [n² - (n-1)²]
= n² - 0² (terms กลางตัดกันทุกคู่)
= n²