ภาพรวมปัญหา
หาผลรวมของอนุกรมกำลังสอง: 2⁰ + 2¹ + 2² + ... + 2ⁿ
ตัวอย่าง
Input: n = 6 Output: 127 Explanation: 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127
วิธีแก้ปัญหา
วิธีลูปธรรมดา - O(n)
int sum = 0;
for (int i = 0; i <= n; i++)
sum += pow(2, i);
วิธีสูตรคณิตศาสตร์ - O(1)
ผลรวม = 2^(n+1) - 1
int calcSeriesSum(int n) {
return (pow(2, n+1) - 1);
}
ตัวอย่างโค้ด C++
#include <iostream>
#include <math.h>
using namespace std;
int calcSeriesSum(int n) {
return (pow(2, n+1) - 1);
}
int main() {
int n = 11;
cout << "Sum of the series 2^0 + 2^1 + ... + 2^" << n << " is " << calcSeriesSum(n);
return 0;
}
ผลลัพธ์
Sum of the series 2^0 + 2^1 + 2^2 +...+ 2^11 is 4095