ภาพรวมปัญหา
หาผลรวมของอนุกรมที่พจน์ที่ i คือผลรวมของเลขคี่ i ตัวแรก: 1 + (1+3) + (1+3+5) + ...
ตัวอย่าง
Input: n = 3 Output: 14 Explanation: (1) + (1+3) + (1+3+5) = 1 + 4 + 9 = 14
วิธีแก้ปัญหา
วิธี Nested Loop - O(n²)
คำนวณเลขคี่สะสมทีละพจน์
วิธีสูตรคณิตศาสตร์ - O(1)
ผลรวมเลขคี่ n ตัว = n²
ผลรวมอนุกรม = Σ n² = n(n+1)(2n+1)/6
ตัวอย่างโค้ด C++
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
return (n * (n+1) * (2*n+1)) / 6;
}
int main() {
int n = 9;
cout << "Sum = " << calcSeriesSum(n);
return 0;
}
ผลลัพธ์
Sum of the series ... + (2*9-1)) is 285