« 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_MIN
11#include <unordered_map>
12using namespace std;
13
14double geometricSum(int k) {
15
16 if(k < 0){
17 return 0;
18 }
19
20 double d = geometricSum(k-1);
21
22 double ans = d + (1/(pow(2, k)));
23
24 return ans;
25}
26
27
28int main()
29{
30 int k;
31 cin >> k;
32 cout << fixed << setprecision(5);
33 cout << geometricSum(k) << endl;
34
35 return 0;
36}