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

求助:Python递归函数实现给定数字的因数查找问题

Fixing Your Recursive Factor Finder

Got it, let's figure out why your recursive factor finder is stuck repeating that message. Recursion relies on two critical pieces: a clear base case to stop the loop, and breaking the problem into smaller subproblems each time you call the function again. If you're seeing that "The factors of x are:" line over and over, you're probably either printing it in every recursive call (instead of just once) or not progressing toward a stopping condition.

Let's walk through a working solution and break down where you might have gone wrong.

Correct Recursive Implementation

Here's a version that collects factors properly, with explanations to avoid the repeated message issue:

def find_factors(n, divisor=1, factors=None):
    # Initialize the factors list and print the header ONLY on the first call
    if factors is None:
        factors = []
        print(f"The factors of {n} are:")
    
    # Base case: stop recursion when we've checked all possible divisors
    if divisor > n:
        # Print the final list of factors
        print(", ".join(map(str, factors)))
        return
    
    # Check if current divisor is a factor of n
    if n % divisor == 0:
        factors.append(divisor)
    
    # Recursive call: move to the next divisor
    find_factors(n, divisor + 1, factors)

# Test it with 12
find_factors(12)

What This Does Right

  • Single Initial Message: We only print "The factors of x are:" once, when the function is first called (since factors starts as None only on that initial run).
  • Clear Base Case: When divisor exceeds n, we've checked every possible number that could be a factor, so we print the result and exit the recursion.
  • Progressive Subproblems: Each recursive call increments the divisor, so we're always moving closer to the base case instead of looping the same check.

Why Your Original Code Likely Failed

Common mistakes here include:

  • Printing the header line inside every recursive call (leading to repeated output)
  • Forgetting to update the divisor in the recursive call (so you keep checking the same number forever)
  • Missing a clear base case (so recursion never stops)

Alternative: Reverse Order Factors

If you want to collect factors from largest to smallest, here's another variation:

def find_factors_reverse(n, divisor=None, factors=None):
    if divisor is None:
        divisor = n
        factors = []
        print(f"The factors of {n} are:")
    
    if divisor < 1:
        print(", ".join(map(str, factors)))
        return
    
    if n % divisor == 0:
        factors.append(divisor)
    
    find_factors_reverse(n, divisor - 1, factors)

find_factors_reverse(12)

This will output: The factors of 12 are: 12, 6, 4, 3, 2, 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:21:27