Skip to content

Commit 6bca714

Browse files
committed
feat: add JacobsthalNumber implementation
1 parent bf8f3bd commit 6bca714

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.maths;
2+
// author: Vraj Prajapati @Rosander0
3+
4+
/**
5+
* The Jacobsthal Sequence is a sequence of integers defined by the recurrence relation:
6+
* J(n) = J(n-1) + 2*J(n-2) with initial values J(0) = 0, J(1) = 1.
7+
* Example: 0, 1, 1, 3, 5, 11, 21, 43, 85, 171, 341...
8+
*
9+
* @see <a href="https://en.wikipedia.org/wiki/Jacobsthal_number">
10+
* Wikipedia: Jacobsthal Number</a>
11+
*/
12+
public final class JacobsthalNumber {
13+
14+
private JacobsthalNumber() {
15+
// Utility class
16+
}
17+
18+
/**
19+
* Calculates the nth term of the Jacobsthal Sequence.
20+
*
21+
* @param n the index of the sequence (must be non-negative)
22+
* @return the nth term of the Jacobsthal Sequence
23+
*/
24+
public static long jacobsthal(final int n) {
25+
if (n < 0) {
26+
throw new IllegalArgumentException("Input must be non-negative!");
27+
}
28+
if (n == 0) {
29+
return 0;
30+
}
31+
if (n == 1) {
32+
return 1;
33+
}
34+
long a = 0;
35+
long b = 1;
36+
long result = 0;
37+
for (int i = 2; i <= n; i++) {
38+
result = b + 2 * a;
39+
a = b;
40+
b = result;
41+
}
42+
return result;
43+
}
44+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.maths;
2+
// author: Vraj Prajapati @Rosander0
3+
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
public class JacobsthalNumberTest {
10+
11+
@Test
12+
public void testBaseCases() {
13+
assertEquals(0, JacobsthalNumber.jacobsthal(0));
14+
assertEquals(1, JacobsthalNumber.jacobsthal(1));
15+
}
16+
17+
@Test
18+
public void testKnownValues() {
19+
assertEquals(1, JacobsthalNumber.jacobsthal(2));
20+
assertEquals(3, JacobsthalNumber.jacobsthal(3));
21+
assertEquals(5, JacobsthalNumber.jacobsthal(4));
22+
assertEquals(11, JacobsthalNumber.jacobsthal(5));
23+
assertEquals(21, JacobsthalNumber.jacobsthal(6));
24+
assertEquals(43, JacobsthalNumber.jacobsthal(7));
25+
assertEquals(85, JacobsthalNumber.jacobsthal(8));
26+
assertEquals(171, JacobsthalNumber.jacobsthal(9));
27+
assertEquals(341, JacobsthalNumber.jacobsthal(10));
28+
}
29+
30+
@Test
31+
public void testInvalidInput() {
32+
assertThrows(IllegalArgumentException.class, () -> JacobsthalNumber.jacobsthal(-1));
33+
}
34+
}

0 commit comments

Comments
 (0)