Skip to content

Commit 1136973

Browse files
authored
Add new algorithm (is_K_power_of_N) to bit manipulation
1 parent 7a0fee4 commit 1136973

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
def is_power(n: int, k: int) -> bool:
2+
"""
3+
Checks if a given integer k is a power of another integer n.
4+
5+
This function determines if there exists an integer x such that n^x = k.
6+
It handles positive integers only and raises an error for non-positive inputs.
7+
For more information, see: https://en.wikipedia.org/wiki/Power_of_two
8+
9+
Args:
10+
n: The base integer (must be a positive integer).
11+
k: The number to check if it's a power of n (must be a positive integer).
12+
13+
Returns:
14+
True if k is a power of n, False otherwise.
15+
16+
Raises:
17+
ValueError: If n or k are not positive integers.
18+
19+
Examples:
20+
>>> is_power(2, 8)
21+
True
22+
>>> is_power(3, 81)
23+
True
24+
>>> is_power(10, 1)
25+
True
26+
>>> is_power(5, 120)
27+
False
28+
>>> is_power(1, 1)
29+
True
30+
>>> is_power(1, 5)
31+
False
32+
>>> is_power(0, 5)
33+
Traceback (most recent call last):
34+
...
35+
ValueError: Both n and k must be positive integers
36+
>>> is_power(4, -16)
37+
Traceback (most recent call last):
38+
...
39+
ValueError: Both n and k must be positive integers
40+
"""
41+
if n <= 0 or k <= 0:
42+
raise ValueError("Both n and k must be positive integers")
43+
44+
if n == 1:
45+
return k == 1
46+
47+
# Repeatedly divide k by n until it's no longer divisible.
48+
while k % n == 0:
49+
k //= n
50+
51+
# If k has been reduced to 1, it was a power of n.
52+
return k == 1
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
58+
doctest.testmod()

0 commit comments

Comments
 (0)