« Find the geometric sum
Problem
Find the geometric sum
Given k, find the geometric sum using recursion i.e.
1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k)
Input format :
Integer k
Output format :
Geometric sum (upto 5 decimal places)
Constraints :
0 <= k <= 1000
Sample Input 1 :
3
Sample Output 1 :
1.87500
Sample Input 2 :
4
Sample Output 2 :
1.93750
Explanation for Sample Input 1:
1+ 1/(2^1) + 1/(2^2) + 1/(2^3) = 1.87500
Solution
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314double geometricSum(int k) {1516 if(k < 0){17 return 0;18 }1920 double d = geometricSum(k-1);2122 double ans = d + (1/(pow(2, k)));2324 return ans;25}262728int main()29{30 int k;31 cin >> k;32 cout << fixed << setprecision(5);33 cout << geometricSum(k) << endl;3435 return 0;36}