Skip to content

Add Sylvester's sequence to maths #5171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 10, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions maths/sylvester_sequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""

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:
raise ValueError(f"The input value of [n={number}] has to be > 0")
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)}")