Skip to content

Commit 0415654

Browse files
committed
feat: Add PadovanSequence Implementation
1 parent 6fbbc94 commit 0415654

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.thealgorithms.maths;
2+
// author: Vraj Prajapati @Rosander0
3+
4+
/**
5+
* The Padovan 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) = P(1) = P(2) = 1.
7+
* Example: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37...
8+
*
9+
* @see <a href="https://en.wikipedia.org/wiki/Padovan_sequence">
10+
* Wikipedia: Padovan Sequence</a>
11+
*/
12+
public final class PadovanSequence {
13+
14+
private PadovanSequence() {
15+
// Utility class
16+
}
17+
18+
/**
19+
* Calculates the nth term of the Padovan Sequence.
20+
*
21+
* @param n the index of the sequence (must be non-negative)
22+
* @return the nth term of the Padovan Sequence
23+
*/
24+
public static long padovan(final int n) {
25+
if (n < 0) {
26+
throw new IllegalArgumentException("Input must be non-negative!");
27+
}
28+
if (n <= 2) {
29+
return 1;
30+
}
31+
long a = 1;
32+
long b = 1;
33+
long c = 1;
34+
long result = 0;
35+
for (int i = 3; i <= n; i++) {
36+
result = a + b;
37+
a = b;
38+
b = c;
39+
c = result;
40+
}
41+
return result;
42+
}
43+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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 PadovanSequenceTest {
10+
11+
@Test
12+
public void testBaseCase() {
13+
assertEquals(1, PadovanSequence.padovan(0));
14+
assertEquals(1, PadovanSequence.padovan(1));
15+
assertEquals(1, PadovanSequence.padovan(2));
16+
}
17+
18+
@Test
19+
public void testKnownValues() {
20+
assertEquals(2, PadovanSequence.padovan(3));
21+
assertEquals(2, PadovanSequence.padovan(4));
22+
assertEquals(3, PadovanSequence.padovan(5));
23+
assertEquals(4, PadovanSequence.padovan(6));
24+
assertEquals(5, PadovanSequence.padovan(7));
25+
assertEquals(7, PadovanSequence.padovan(8));
26+
assertEquals(9, PadovanSequence.padovan(9));
27+
assertEquals(12, PadovanSequence.padovan(10));
28+
}
29+
30+
@Test
31+
public void testInvalidInput() {
32+
assertThrows(IllegalArgumentException.class,
33+
() -> PadovanSequence.padovan(-1));
34+
}
35+
}

0 commit comments

Comments
 (0)