Skip to content
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
* [Highest Set Bit](bit_manipulation/highest_set_bit.py)
* [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py)
* [Is Even](bit_manipulation/is_even.py)
* [Is K Power Of N](bit_manipulation/is_k_power_of_n.py)
* [Is Power Of Two](bit_manipulation/is_power_of_two.py)
* [Largest Pow Of Two Le Num](bit_manipulation/largest_pow_of_two_le_num.py)
* [Missing Number](bit_manipulation/missing_number.py)
Expand Down
59 changes: 59 additions & 0 deletions bit_manipulation/is_k_power_of_n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
def is_power(base: int, number: int) -> bool:
"""
Checks if a given integer `number` is a power of another integer `base`.

This function determines if there exists an integer x such that base^x = number.
It handles positive integers only and raises an error for non-positive inputs.
For more information, see: https://en.wikipedia.org/wiki/Power_of_two

Args:
base: The base integer (must be a positive integer).
number: The number to check if it's a power of base
(must be a positive integer).

Returns:
True if number is a power of base, False otherwise.

Raises:
ValueError: If base or number are not positive integers.

Examples:
>>> is_power(2, 8)
True
>>> is_power(3, 81)
True
>>> is_power(10, 1)
True
>>> is_power(5, 120)
False
>>> is_power(1, 1)
True
>>> is_power(1, 5)
False
>>> is_power(0, 5)
Traceback (most recent call last):
...
ValueError: Both base and number must be positive integers
>>> is_power(4, -16)
Traceback (most recent call last):
...
ValueError: Both base and number must be positive integers
"""
if base <= 0 or number <= 0:
raise ValueError("Both base and number must be positive integers")

if base == 1:
return number == 1

# Repeatedly divide number by base until it's no longer divisible.
while number % base == 0:
number //= base

# If number has been reduced to 1, it was a power of base.
return number == 1


if __name__ == "__main__":
import doctest

doctest.testmod()