forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sylvester_sequence.py
44 lines (33 loc) · 1.05 KB
/
sylvester_sequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Calculates the nth number in Sylvester's sequence
Source:
https://en.wikipedia.org/wiki/Sylvester%27s_sequence
"""
def sylvester(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Sylvester's sequence
>>> sylvester(8)
113423713055421844361000443
>>> sylvester(-1)
Traceback (most recent call last):
...
ValueError: The input value of [n=-1] has to be > 0
>>> sylvester(8.0)
Traceback (most recent call last):
...
AssertionError: The input value of [n=8.0] is not an integer
"""
assert isinstance(number, int), f"The input value of [n={number}] is not an integer"
if number == 1:
return 2
elif number < 1:
msg = f"The input value of [n={number}] has to be > 0"
raise ValueError(msg)
else:
num = sylvester(number - 1)
lower = num - 1
upper = num
return lower * upper + 1
if __name__ == "__main__":
print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")