-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFor22.java
More file actions
24 lines (21 loc) · 605 Bytes
/
For22.java
File metadata and controls
24 lines (21 loc) · 605 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
package fori;
public class For22 {
public static void main(String[] args) {
double result = solution(3,0.5);
System.out.println(result);
// 1 + 0.5/1! + 0.5^2/2! + 0.5^3/3!
}
public static double solution(int n, double x) {
double sum = 1; // sum + x^i/i! + x^2/2! + x^3/3! + ...
int factorial = 1;
double pow = x;
for (int i = 1; i <= n; i++) {
// pow = x^i
// factorial = i!
sum += pow / factorial;
factorial *= i;
pow *= x; // x * x
}
return sum;
}
}