|
| 1 | +def is_k_power_of_n(n: int, k: int) -> bool: |
| 2 | + """ |
| 3 | + Given two positive integers, n and k, this function determines if k |
| 4 | + is a power of n. A number k is a power of n if k = n^x for some |
| 5 | + non-negative integer x. |
| 6 | +
|
| 7 | + >>> is_k_power_of_n(2, 8) |
| 8 | + True |
| 9 | + >>> is_k_power_of_n(3, 10) |
| 10 | + False |
| 11 | + >>> is_k_power_of_n(5, 5) |
| 12 | + True |
| 13 | + >>> is_k_power_of_n(10, 1000) |
| 14 | + True |
| 15 | + >>> is_k_power_of_n(4, 2) |
| 16 | + False |
| 17 | + >>> is_k_power_of_n(1, 1) |
| 18 | + True |
| 19 | + >>> is_k_power_of_n(1, 5) |
| 20 | + False |
| 21 | + >>> is_k_power_of_n(0, 16) |
| 22 | + Traceback (most recent call last): |
| 23 | + ... |
| 24 | + ValueError: Both n and k must be positive integers |
| 25 | + >>> is_k_power_of_n(2, -8) |
| 26 | + Traceback (most recent call last): |
| 27 | + ... |
| 28 | + ValueError: Both n and k must be positive integers |
| 29 | + >>> is_k_power_of_n(2, 'a') |
| 30 | + Traceback (most recent call last): |
| 31 | + ... |
| 32 | + TypeError: n and k must be integers |
| 33 | + """ |
| 34 | + if not isinstance(n, int) or not isinstance(k, int): |
| 35 | + raise TypeError("n and k must be integers") |
| 36 | + |
| 37 | + if n <= 0 or k <= 0: |
| 38 | + raise ValueError("Both n and k must be positive integers") |
| 39 | + |
| 40 | + if n == 1: |
| 41 | + return k == 1 |
| 42 | + |
| 43 | + while k % n == 0: |
| 44 | + k //= n |
| 45 | + return k == 1 |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + import doctest |
| 50 | + |
| 51 | + doctest.testmod() |
| 52 | +``` |
0 commit comments