forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeometricSum.java
More file actions
36 lines (32 loc) · 698 Bytes
/
Copy pathGeometricSum.java
File metadata and controls
36 lines (32 loc) · 698 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
package recursion1.Assignment;
import java.util.Scanner;
/*Given k, find the geometric sum i.e.
1 + 1/2 + 1/4 + 1/8 + ... + 1/(2^k)
using recursion.
Input format :
Integer k
Output format :
Geometric sum
Constraints :
0 <= k <= 1000
Sample Input 1 :
3
Sample Output 1 :
1.875
Sample Input 2 :
4
Sample Output 2 :
1.93750*/
public class GeometricSum {
public static double geometricSum(int k) {
if (k == 0) {
return 1;
}
return (geometricSum(k - 1) + 1 / Math.pow(2, k));
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int k = scan.nextInt();
System.out.println(geometricSum(k));
}
}