Skip to content

Commit 0d2a2bb

Browse files
committed
feat: Add PadovanSequence Implementation
1 parent 0388455 commit 0d2a2bb

2 files changed

Lines changed: 79 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+
3+
/**
4+
* The Padovan Sequence is a sequence of integers defined by the recurrence relation:
5+
* P(n) = P(n-2) + P(n-3) with initial values P(0) = P(1) = P(2) = 1.
6+
* Example: 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37...
7+
*
8+
* @see <a href="https://en.wikipedia.org/wiki/Padovan_sequence">
9+
* Wikipedia: Padovan Sequence</a>
10+
* @author Vraj Prajapati (@Rosander0)
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. Received: " + n);
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: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
/**
9+
* @author Vraj Prajapati (@Rosander0)
10+
*/
11+
public class PadovanSequenceTest {
12+
13+
@Test
14+
public void testBaseCase() {
15+
assertEquals(1, PadovanSequence.padovan(0));
16+
assertEquals(1, PadovanSequence.padovan(1));
17+
assertEquals(1, PadovanSequence.padovan(2));
18+
}
19+
20+
@Test
21+
public void testKnownValues() {
22+
assertEquals(2, PadovanSequence.padovan(3));
23+
assertEquals(2, PadovanSequence.padovan(4));
24+
assertEquals(3, PadovanSequence.padovan(5));
25+
assertEquals(4, PadovanSequence.padovan(6));
26+
assertEquals(5, PadovanSequence.padovan(7));
27+
assertEquals(7, PadovanSequence.padovan(8));
28+
assertEquals(9, PadovanSequence.padovan(9));
29+
assertEquals(12, PadovanSequence.padovan(10));
30+
}
31+
32+
@Test
33+
public void testInvalidInput() {
34+
assertThrows(IllegalArgumentException.class, () -> PadovanSequence.padovan(-1));
35+
}
36+
}

0 commit comments

Comments
 (0)