forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArithmeticProgression.java
44 lines (40 loc) · 1.56 KB
/
ArithmeticProgression.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
package com.jwetherell.algorithms.sequence;
/**
* Compute the result of adding a sequence of numbers from N (startNumber) to N+X (startNumber+numberOfNumbersToCompute)
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Arithmetic_progression">Arithmetic Progression (Wikipedia)</a>
* <br>
* @author Justin Wetherell <[email protected]>
*/
public class ArithmeticProgression {
/**
* Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber).
* <p>
* e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X)
*/
public static final long sequenceTotalUsingLoop(int startNumber, int numberOfNumbersToCompute) {
int start = startNumber;
int length = numberOfNumbersToCompute;
long result = 0L;
while (length > 0) {
result += start++;
length--;
}
return result;
}
/**
* Compute the result of adding X (numberOfNumbersToCompute) together starting at N (startNumber) using triangular numbers.
* <p>
* e.g. result = N + (N+1) + (N+2) + (N+3) + ..... + (N+X)<br>
* <br>
* @see <a href="https://en.wikipedia.org/wiki/Triangular_number">Triangular Number (Wikipedia)</a>
*/
public static final long sequenceTotalUsingTriangularNumbers(int startNumber, int numberOfNumbersToCompute) {
// n*(n+1)/2
final int start = startNumber;
final int length = numberOfNumbersToCompute;
long result = length * (length + 1) / 2;
result += (start - 1) * length;
return result;
}
}