Skip to content
Closed
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
58 changes: 58 additions & 0 deletions bit_manipulation/is_K_power_of_n.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
def is_power(base: int, number: int) -> bool:

Check failure on line 1 in bit_manipulation/is_K_power_of_n.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

bit_manipulation/is_K_power_of_n.py:1:1: N999 Invalid module name: 'is_K_power_of_n'
"""
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).

Check failure on line 11 in bit_manipulation/is_K_power_of_n.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

bit_manipulation/is_K_power_of_n.py:11:89: E501 Line too long (89 > 88)

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()
Loading