File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ()
You can’t perform that action at this time.
0 commit comments