Skip to content

Commit 2289014

Browse files
committed
feat: add Lucas numbers algorithm with doctests
1 parent 456d644 commit 2289014

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

maths/lucas_numbers.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
def lucas_number(n: int) -> int:
2+
"""
3+
Returns the n-th Lucas number using an iterative approach.
4+
The Lucas numbers are an integer sequence where each term is the sum of the
5+
two preceding terms, starting with 2 and 1.
6+
7+
Reference: https://en.wikipedia.org/wiki/Lucas_number
8+
9+
>>> lucas_number(0)
10+
2
11+
>>> lucas_number(1)
12+
1
13+
>>> lucas_number(5)
14+
11
15+
>>> lucas_number(10)
16+
123
17+
>>> lucas_number(-3)
18+
Traceback (most recent call last):
19+
...
20+
ValueError: n must be a non-negative integer.
21+
"""
22+
if n < 0:
23+
raise ValueError("n must be a non-negative integer.")
24+
25+
if n == 0:
26+
return 2
27+
if n == 1:
28+
return 1
29+
30+
a, b = 2, 1
31+
for _ in range(2, n + 1):
32+
a, b = b, a + b
33+
return b
34+
35+
36+
if __name__ == "__main__":
37+
import doctest
38+
39+
doctest.testmod()

0 commit comments

Comments
 (0)