Skip to content

Add new algorithm (is_K_power_of_N) to bit manipulation #12873

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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(n: int, k: 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'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Please provide descriptive name for the parameter: k

"""
Checks if a given integer k is a power of another integer n.

This function determines if there exists an integer x such that n^x = k.
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:
n: The base integer (must be a positive integer).
k: The number to check if it's a power of n (must be a positive integer).

Returns:
True if k is a power of n, False otherwise.

Raises:
ValueError: If n or k 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 n and k must be positive integers
>>> is_power(4, -16)
Traceback (most recent call last):
...
ValueError: Both n and k must be positive integers
"""
if n <= 0 or k <= 0:
raise ValueError("Both n and k must be positive integers")

if n == 1:
return k == 1

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

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


if __name__ == "__main__":
import doctest

doctest.testmod()
Loading