-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGeometricSequence.java
49 lines (39 loc) · 1.03 KB
/
GeometricSequence.java
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
public class GeometricSequence extends Sequence {
int initial;
int current_element, next_element;
int ratio;
public GeometricSequence(int e0, int r) {
initial = e0;
current_element = e0;
next_element = e0 * r;
ratio = r;
}
public int get_next_element() {
indx++;
current_element *= ratio;
return current_element;
}
public int get_prev_element() {
indx--;
current_element /= ratio;
return current_element;
}
public int get_element() {
return current_element;
}
public int get_element_by_index(int index) {
if (indx >= index) {
index = Math.abs(index - indx);
while (index-- > 0) this.get_prev_element();
} else {
index = Math.abs(index - indx);
while (index-- > 0) this.get_next_element();
}
return this.get_element();
}
public int get_sum_of_elements(int start, int end) {
int sumEnd = (int)((initial * (1 - Math.pow(ratio, end + 1))) / (1 - ratio));
int sumStart = start == 0 ? 0 : (int)((initial * (1 - Math.pow(ratio, start))) / (1 - ratio));
return sumEnd - sumStart;
}
}