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

Python实现1-100的FizzBuzz与质数判定及代码修正咨询

Fixing the FizzBuzz + Prime Detection Code

Let's walk through the issues in your code one by one, then fix them to meet the requirements—including correctly identifying 91 as a non-prime:

Key Problems in the Original Code

  • FizzBuzz Condition Order: The code checks divisibility by 3 first, so numbers divisible by both 3 and 5 (like 15) will never trigger the "FizzBuzz" case. We need to check the combined condition first.
  • Range Mismatch: range(100) generates numbers from 0 to 99, but the problem asks for 1 to 100. Use range(1, 101) instead.
  • Broken Prime Detection:
    • The condition x%x == 0 is always true for any x ≠ 0, so it doesn't help identify primes.
    • 1 is incorrectly labeled as prime (it's not a prime number).
    • Odd numbers like 91 (7×13) are falsely marked as prime because the code doesn't check for divisors other than 2.
  • Case Inconsistency: The code prints "buzz" instead of "Buzz" as specified.

Corrected Code with Explanations

Here's the fixed code that addresses all these issues:

def is_prime(n):
    # Handle edge cases first
    if n <= 1:
        return False
    if n == 2:
        return True
    # Even numbers greater than 2 aren't prime
    if n % 2 == 0:
        return False
    # Check divisors from 3 up to sqrt(n), stepping by 2 (only odd divisors)
    for i in range(3, int(n**0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

# Iterate from 1 to 100 inclusive
for x in range(1, 101):
    if x % 3 == 0 and x % 5 == 0:
        print("FizzBuzz", x)
    elif x % 3 == 0:
        print("Fizz", x)
    elif x % 5 == 0:
        print("Buzz", x)
    elif is_prime(x):
        print("Prime number", x)
    # Optional: Print the number itself if none of the above apply
    else:
        print(x)

Breakdown of Fixes:

  1. FizzBuzz Logic: We first check if x is divisible by both 3 and 5, ensuring "FizzBuzz" is printed for those numbers before checking individual divisibility by 3 or 5.
  2. Prime Check Function:
    • The is_prime function properly handles edge cases (1 is not prime, 2 is the only even prime).
    • For odd numbers greater than 2, it checks divisors up to the square root of n (since factors larger than sqrt(n) would have a corresponding smaller factor). This efficiently catches cases like 91 (divisible by 7).
  3. Range: range(1,101) correctly covers numbers from 1 to 100.
  4. Case Consistency: "Buzz" is now capitalized as specified.

Testing 91:

When x=91, the is_prime function checks divisors starting at 3. When i=7, 91%7 ==0, so it returns False, correctly identifying 91 as non-prime.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:42:55