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).

defprimecheck(a,b):
printlist=[]
if a > 1:
    for i inrange(a,b+1):
        for j inrange(2,i):
            if i % j == 0:
                breakelse:
            printlist.append(i)
iflen(printlist) == 0:
    return0else:
    returnlen(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.

defsieve_of_eratosthenes(start, end):
    if start > end:
        raise AssertionError
    
#     end = end + 1 # If end is inclusive, then uncomment this line.if end < 2:
        return0
    
    sieve = [i for i inrange(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 inrange(count, size):
            num = sieve[i]
            if num != p and num % p == 0:
                sieve[i] = 0if count == size-1:
            break
        
        count += 1while sieve[count] == 0:
            count += 1if 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 = 0for p in sieve:
        if p == 0or p < start:
            continue
        num_of_primes += 1print(sieve)
    return num_of_primes


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

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