Skip to content Skip to sidebar Skip to footer

Python Beginner Question “Prime Number Count”

def prime_count(a, b): for i in range(a,b): if i % 2 != 0: return sum(i) else: return 0 ' I am a beginner programmer, I have been practic

Solution 1:

it is an interesting problem that you are solving. You will have to run two-loops here. One to iterate from a to b and the inner loop to check if each element in a -->b is prime or not (the inner loop should run from 2 to j in [a,b).

def primecheck(a,b):
printlist=[]
if a > 1:
    for i in range(a,b+1):
        for j in range(2,i):
            if i % j == 0:
                break
        else:
            printlist.append(i)
if len(printlist) == 0:
    return 0
else:
    return len(printlist), printlist

Try this out.


Solution 2:

As people say in the comment section, calling sum() is what's causing an error.

But, even if you somehow got that part right, you wouldn't quite get what you want. Maybe you were just trying a simple for loop to check if numbers are odd...?

Anyway, I normally like using Sieve of Eratosthenes to generate prime numbers because it's simple.

def sieve_of_eratosthenes(start, end):
    if start > end:
        raise AssertionError
    
#     end = end + 1 # If end is inclusive, then uncomment this line.
    if end < 2:
        return 0
    
    sieve = [i for i in range(2, end)] # Initialize an array of number from 2 to end.
    size = len(sieve)
    p = 2 # Initial prime.
    count = 0

    # This block implements Sieve of Eratosthenes.
    while count < size:
        for i in range(count, size):
            num = sieve[i]
            if num != p and num % p == 0:
                sieve[i] = 0

        if count == size-1:
            break
        
        count += 1
        while sieve[count] == 0:
            count += 1
            if count == size-1:
                break
        p = sieve[count] # Update the next prime.
     
    # This block calculates the numbers of primes between start and end.
    num_of_primes = 0
    for p in sieve:
        if p == 0 or p < start:
            continue
        num_of_primes += 1
        
    print(sieve)
    return num_of_primes


sieve_of_eratosthenes(1, 100) # This should return 25.

Post a Comment for "Python Beginner Question “Prime Number Count”"