Skip to content

Commit 43203a5

Browse files
committed
feat: add PerrinNumber implementation
1 parent bf8f3bd commit 43203a5

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.thealgorithms.maths;
2+
// author: Vraj Prajapati @Rosander0
3+
4+
/**
5+
* The Perrin Sequence is a sequence of integers defined by the recurrence relation:
6+
* P(n) = P(n-2) + P(n-3) with initial values P(0) = 3, P(1) = 0, P(2) = 2.
7+
* Example: 3, 0, 2, 3, 2, 5, 5, 7, 10, 12, 17, 22, 29, 39, 51...
8+
*
9+
* Note: The Perrin Sequence uses the same recurrence relation as the Padovan Sequence
10+
* but has different initial values.
11+
*
12+
* @see <a href="https://en.wikipedia.org/wiki/Perrin_number">
13+
* Wikipedia: Perrin Number</a>
14+
* @see PadovanSequence
15+
*/
16+
public final class PerrinNumber {
17+
18+
private PerrinNumber() {
19+
// Utility class
20+
}
21+
22+
/**
23+
* Calculates the nth term of the Perrin Sequence.
24+
*
25+
* @param n the index of the sequence (must be non-negative)
26+
* @return the nth term of the Perrin Sequence
27+
*/
28+
public static long perrin(final int n) {
29+
if (n < 0) {
30+
throw new IllegalArgumentException("Input must be non-negative!");
31+
}
32+
if (n == 0) {
33+
return 3;
34+
}
35+
if (n == 1) {
36+
return 0;
37+
}
38+
if (n == 2) {
39+
return 2;
40+
}
41+
long a = 3;
42+
long b = 0;
43+
long c = 2;
44+
long result = 0;
45+
for (int i = 3; i <= n; i++) {
46+
result = a + b;
47+
a = b;
48+
b = c;
49+
c = result;
50+
}
51+
return result;
52+
}
53+
}
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 PerrinNumberTest {
10+
11+
@Test
12+
public void testBaseCases() {
13+
assertEquals(3, PerrinNumber.perrin(0));
14+
assertEquals(0, PerrinNumber.perrin(1));
15+
assertEquals(2, PerrinNumber.perrin(2));
16+
}
17+
18+
@Test
19+
public void testKnownValues() {
20+
assertEquals(3, PerrinNumber.perrin(3));
21+
assertEquals(2, PerrinNumber.perrin(4));
22+
assertEquals(5, PerrinNumber.perrin(5));
23+
assertEquals(5, PerrinNumber.perrin(6));
24+
assertEquals(7, PerrinNumber.perrin(7));
25+
assertEquals(10, PerrinNumber.perrin(8));
26+
assertEquals(12, PerrinNumber.perrin(9));
27+
assertEquals(17, PerrinNumber.perrin(10));
28+
}
29+
30+
@Test
31+
public void testInvalidInput() {
32+
assertThrows(IllegalArgumentException.class, () -> PerrinNumber.perrin(-1));
33+
}
34+
}

0 commit comments

Comments
 (0)