-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeomatricSum.java
More file actions
44 lines (40 loc) · 1009 Bytes
/
GeomatricSum.java
File metadata and controls
44 lines (40 loc) · 1009 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
// Geometric Sum
// Send Feedback
// 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 (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
import java.util.Scanner;
public class GeomatricSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Give Integer : ");
int k = s.nextInt();
double ans = findGeometricSum(k);
System.out.print("Output : " + ans);
s.close();
}
public static double findGeometricSum(int k) {
if (k == 0) {
return 1;
} else {
double a = 1 / (Math.pow(2, k));
return a + findGeometricSum(k - 1);
}
}
}