Home > Backend Development > Python Tutorial > How to Correctly Print Prime Numbers in Python: Resolving an Issue with Odd Output

How to Correctly Print Prime Numbers in Python: Resolving an Issue with Odd Output

Mary-Kate Olsen
Release: 2024-10-21 12:38:02
Original
1015 people have browsed it

How to Correctly Print Prime Numbers in Python: Resolving an Issue with Odd Output

Printing Prime Numbers in Python

In an attempt to list prime numbers from 1 to 100, a Python user encountered an issue where the output displayed odd numbers instead of primes. To address this, we'll delve into the issue and provide a revised solution.

The initial code, as shown below, iterates over numbers from 1 to 100, and for each number, it checks if it is divisible by any number from 2 to itself:

<code class="python">for num in range(1, 101):
    for i in range(2, num):
        if num % i == 0:
            break
        else:
            print(num)
            break</code>
Copy after login

The problem with this approach lies in the nested loop's termination criteria. Once a number is found to be divisible by a factor i, the inner loop breaks and the print(num) statement is executed. However, the outer loop then starts checking the same number with the next value of i.

To resolve this, we need to update the loop to check divisibility by all numbers from 2 to the square root of num. If none of these divisors divides num, it is likely prime. The corrected code would be:

<code class="python">for num in range(2, 101):
    prime = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            prime = False
            break
    if prime:
        print(num)</code>
Copy after login

This solution efficiently detects prime numbers by iteratively checking divisibility by smaller factors. As a result, the output will accurately display the prime numbers from 1 to 100.

The above is the detailed content of How to Correctly Print Prime Numbers in Python: Resolving an Issue with Odd Output. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template