You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将判断基数幂的is_power_of非递归函数改写为递归函数?

递归实现 is_power_of 函数

问题回顾

需要实现一个递归函数,判断给定数字是否为指定正整数基数的幂,返回布尔值。

原非递归代码的局限

原代码仅检查了基数的1到3次幂,无法处理更高次幂的情况(比如is_power_of(16, 2)会错误返回False),递归实现可以解决这个问题,同时更贴合幂运算的逻辑本质。

递归实现思路

通过将问题拆解为更小的子问题实现递归:

  • 终止条件1:若number等于1,返回True(任何正整数的0次幂为1)
  • 终止条件2:若number小于base或无法被base整除,返回False
  • 递归步骤:将number除以base,递归调用自身判断结果

递归代码实现

def is_power_of(number, base):
    # 处理number为1的情况(base^0=1)
    if number == 1:
        return True
    # 若number小于base或无法被base整除,直接返回False
    if number < base or number % base != 0:
        return False
    # 递归调用,将number缩小后继续判断
    return is_power_of(number // base, base)

# 测试用例
print(is_power_of(8, 2))    # 输出: True(2^3=8)
print(is_power_of(64, 4))   # 输出: True(4^3=64)
print(is_power_of(16, 2))   # 输出: True(2^4=16)
print(is_power_of(1, 5))    # 输出: True(5^0=1)
print(is_power_of(5, 2))    # 输出: False

代码说明

  • 基于题目中基数为正整数的约束,无需处理base为0或负数的情况
  • 递归过程不断将number缩小为number//base,直到触发终止条件,可处理任意次幂的判断需求

内容的提问来源于stack exchange,提问作者LAWRENCE APPIAH-NUAMAH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:10:03