简体   繁体   中英

All prime numbers within a range

I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime... Any assistant will be most appreciated !

def primes():
    start = int(input("Enter the starting number: "))
    end = int(input("Enter the ending number: "))
    num = 0
    i = 0
    ctr = 0
    for num in range(start,end+1,1):
        ctr = 0
        for i in range(2,num//2,1):
            if num % i == 0 :
                ctr = ctr + 1
                break
        if (ctr==0 and num != 1):
            print(num)
for i in range(2,num//2,1):

Lets check this snippet of code when num = 4,it becomes

for i in range(2,2,1):

Now we see the problem. Solution..?

for i in range(2,(num//2)+1,1):

The following methods are all possible prime checkers you might use to check within your range:

def isPrime(Number):  # slow
    return 2 in [Number, 2 ** Number % Number]


def isprime(n):  # out of memory errors with big numbers
    """check if integer n is a prime"""
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
        # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True


def is_prime(n):  # Best until now
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(n ** 0.5)
    f = 5
    while f <= r:
        # print '\t', f
        if n % f == 0:
            return False
        if n % (f + 2) == 0:
            return False
        f += 6
    return True
for i in range(2,num//2,1):

Above line is wrong. You are iterating from 2 to num / 2 - 1 .
You should iterate from 2 to sqrt(num) . ( range(2, int(math.sqrt(n)) + 1) )
Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM