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

递归实现幂次判断函数求助:仅用指定工具函数完成需求

判断数值是否为指定底数的正整数次幂的问题解决

需求明确

需要实现函数check_is_power(base: int, number: int),当存在正整数exp满足base ** exp == number时返回True,否则返回False,且仅能使用给定的四个辅助函数:

def add(x: float, y: float) -> float:
    return x + y

def subtract_1(x: int) -> int:
    return x - 1

def is_odd(n: int) -> bool:
    return n % 2 == 1

def divide_by_2(n: int) -> int:
    return n // 2

原代码问题分析

你的代码存在两个核心错误:

  1. 硬编码底数逻辑:不管传入的base是什么,都直接对number执行divide_by_2,这只适用于base=2的场景,其他底数(如3、5)完全失效。
  2. 缺失关键判断:没有检查number是否能被base整除,也未处理number < base这类终止条件,会导致递归逻辑错误甚至无限递归。

解决方案

我们先基于给定函数实现必要的辅助功能,再构建正确的递归逻辑:

步骤1:实现辅助函数

def subtract(a: int, b: int) -> int:
    # 用subtract_1实现a - b的减法逻辑
    if b == 0:
        return a
    return subtract(subtract_1(a), subtract_1(b))

def divide_and_check(a: int, b: int) -> tuple[int, bool]:
    # 返回(商, 是否能被整除)的元组
    if a < b:
        return (0, False)
    if a == b:
        return (1, True)
    # 递归减b计算商
    quotient, is_divisible = divide_and_check(subtract(a, b), b)
    # 用add累加商,转int是因为add返回float类型
    return (int(add(quotient, 1.0)), is_divisible)

步骤2:实现核心判断函数

def check_is_power(base: int, number: int) -> bool:
    # 处理base为1的特殊情况:只有number=1时满足条件
    if base == 1:
        return number == 1
    # 处理number为1的情况:base>1时,1不是base的正整数次幂(exp需为正整数)
    if number == 1:
        return False
    # 当number等于base时,exp=1,直接返回True
    if number == base:
        return True
    # number小于base时,不可能是base的正整数次幂
    if number < base:
        return False
    # 判断number是否能被base整除,同时得到商
    quotient, is_divisible = divide_and_check(number, base)
    if not is_divisible:
        return False
    # 递归检查商是否是base的幂
    return check_is_power(base, quotient)

测试验证

  • check_is_power(2, 16) → True(2^4=16)
  • check_is_power(3, 17) → False(17无法被3整除)
  • check_is_power(3, 9) → True(3^2=9)
  • check_is_power(5, 1) → False(base>1时,1不是正整数次幂)
  • check_is_power(1, 1) → True(1的任何次幂都是1)

内容的提问来源于stack exchange,提问作者Avi Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:36:12