-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeometricSum.cpp
More file actions
53 lines (40 loc) · 793 Bytes
/
Copy pathGeometricSum.cpp
File metadata and controls
53 lines (40 loc) · 793 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Title: Geometric Sum
Problem statement
Given k, find the geometric sum i.e.
1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k)
Note: using recursion.
Detailed explanation ( Input/output format, Notes, Images )
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
*/
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
float GeometricSum(int k) {
if(k == 0) {
return 1;
}
return 1 / pow(2, k) + GeometricSum(k - 1);
}
int main() {
int k;
cin >> k;
cout << fixed << setprecision(5);
cout << GeometricSum(k) << endl;
}