Home > Enterprise >  I'm getting a weird error for printing n prime numbers
I'm getting a weird error for printing n prime numbers

Time:07-07

def prime(n):
    if n==2 or n==3:
        return True
    if n==1:
        return False
    f=True
    for i in range(2,int(n**0.5) 1):
        if n%i==0:
            f=False 
            break
    return f
def n_primes(n):
    primes=[2,3,5,7]
    k=10
    count=4
    itr=[1,3,7,9]
    while count!=n:
        for i in itr:
            if prime(k i):
               primes.append(k i)
               count =1 
        k =10
    return primes
print(len(n_primes(100)))

This program is returning n primes for almost any number that I've tried except 100 for 100 it's returning 101 prime numbers I can easily get 100 primes by slicing the list but I want to know what is wrong with my program I've tried terminating the while loop using count, length of the list but result is not changing

CodePudding user response:

Not only for 100, it would be an issue for other numbers as well. For example:

print(n_primes(5))

[2, 3, 5, 7, 11, 13, 17, 19]

It is because you do the count!=n check only once every 4 iterations (after iterating through the 4 numbers of itr). Also, you should do count<n otherwise you would go into an infinite loop. To avoid infinite loop and get exact number of primes do another check after incrementing count.

def prime(n):
    if n==2 or n==3:
        return True
    if n==1:
        return False
    f=True
    for i in range(2,int(n**0.5) 1):
        if n%i==0:
            f=False 
            break
    return f

def n_primes(n):
    primes=[2,3,5,7]
    k=10
    count=4
    itr=[1,3,7,9]
    while count<n:
        for i in itr:
            if prime(k i):
               primes.append(k i)
               count =1
               if (count>=n):
                  break 
        k =10
    return primes

print(n_primes(5)) # prints [2, 3, 5, 7, 11]
print(len(n_primes(100))) # prints 100
  • Related