Skip to content

Commit 618f9ca

Browse files
jrinder42cclauss
andauthored
Add Proth number to maths (TheAlgorithms#5246)
* Add Proth number to maths * Add test for 0 and more informative output * Fixing test failure issue - unused variable * Update proth_number.py Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent bb37ebb commit 618f9ca

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

maths/proth_number.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
Calculate the nth Proth number
3+
4+
Source:
5+
https://handwiki.org/wiki/Proth_number
6+
"""
7+
8+
import math
9+
10+
11+
def proth(number: int) -> int:
12+
"""
13+
:param number: nth number to calculate in the sequence
14+
:return: the nth number in Proth number
15+
16+
Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3
17+
18+
>>> proth(6)
19+
25
20+
21+
>>> proth(0)
22+
Traceback (most recent call last):
23+
...
24+
ValueError: Input value of [number=0] must be > 0
25+
26+
>>> proth(-1)
27+
Traceback (most recent call last):
28+
...
29+
ValueError: Input value of [number=-1] must be > 0
30+
31+
>>> proth(6.0)
32+
Traceback (most recent call last):
33+
...
34+
TypeError: Input value of [number=6.0] must be an integer
35+
"""
36+
37+
if not isinstance(number, int):
38+
raise TypeError(f"Input value of [number={number}] must be an integer")
39+
40+
if number < 1:
41+
raise ValueError(f"Input value of [number={number}] must be > 0")
42+
elif number == 1:
43+
return 3
44+
elif number == 2:
45+
return 5
46+
else:
47+
block_index = number // 3
48+
"""
49+
+1 for binary starting at 0 i.e. 2^0, 2^1, etc.
50+
+1 to start the sequence at the 3rd Proth number
51+
Hence, we have a +2 in the below statement
52+
"""
53+
block_index = math.log(block_index, 2) + 2
54+
block_index = int(block_index)
55+
56+
proth_list = [3, 5]
57+
proth_index = 2
58+
increment = 3
59+
for block in range(1, block_index):
60+
for move in range(increment):
61+
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
62+
proth_index += 1
63+
increment *= 2
64+
65+
return proth_list[number - 1]
66+
67+
68+
if __name__ == "__main__":
69+
for number in range(11):
70+
value = 0
71+
try:
72+
value = proth(number)
73+
except ValueError:
74+
print(f"ValueError: there is no {number}th Proth number")
75+
continue
76+
77+
print(f"The {number}th Proth number: {value}")

0 commit comments

Comments
 (0)