Skip to content

Commit a0a7ca0

Browse files
committed
Add Padovan Sequence algorithm in maths
1 parent 8934bab commit a0a7ca0

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

maths/padovan_sequence.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def padovan_sequence(n: int) -> int:
2+
"""
3+
Return the n-th term of the Padovan Sequence.
4+
The Padovan sequence is the sequence of integers P(n) defined by the initial values
5+
P(0) = P(1) = P(2) = 1 and the recurrence relation P(n) = P(n-2) + P(n-3).
6+
7+
https://en.wikipedia.org/wiki/Padovan_sequence
8+
9+
:param n: The index of the term to return.
10+
:return: The n-th term of the Padovan Sequence.
11+
12+
>>> padovan_sequence(0)
13+
1
14+
>>> padovan_sequence(1)
15+
1
16+
>>> padovan_sequence(2)
17+
1
18+
>>> padovan_sequence(3)
19+
2
20+
>>> padovan_sequence(4)
21+
2
22+
>>> padovan_sequence(5)
23+
3
24+
>>> padovan_sequence(10)
25+
12
26+
>>> padovan_sequence(-1)
27+
Traceback (most recent call last):
28+
...
29+
ValueError: Input must be a non-negative integer.
30+
"""
31+
if not isinstance(n, int) or n < 0:
32+
raise ValueError("Input must be a non-negative integer.")
33+
34+
if n <= 2:
35+
return 1
36+
37+
p_prev_3, p_prev_2, p_prev_1 = 1, 1, 1
38+
39+
for _ in range(3, n + 1):
40+
curr = p_prev_2 + p_prev_3
41+
p_prev_3, p_prev_2, p_prev_1 = p_prev_2, p_prev_1, curr
42+
43+
return p_prev_1
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()
48+
print("Doctests passed!")

0 commit comments

Comments
 (0)