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. Userange(1, 101)instead. - Broken Prime Detection:
- The condition
x%x == 0is 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.
- The condition
- 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:
- FizzBuzz Logic: We first check if
xis divisible by both 3 and 5, ensuring "FizzBuzz" is printed for those numbers before checking individual divisibility by 3 or 5. - Prime Check Function:
- The
is_primefunction 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).
- The
- Range:
range(1,101)correctly covers numbers from 1 to 100. - 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
相关产品推荐
相关产品推荐

