How to get N prime numbers instead of prime numbers until user input in Python

Question:

I have a working code to find prime numbers. Code asks for user to select a number and returns the prime numbers untill user input. However I am trying to reutrn the user input as N.

def calculate_n_prime():
    n_numbers = int(input("How many prime numbers would you like to see? "))



    for num in range(2, n_numbers):
        if num > 1:
            for i in range(2, num):
                if (num % i) == 0:
                    break
            else:
                print(num, end="-")



if __name__ == "__main__":
    calculate_n_prime()

Current code returns = [2,3,5,7]

I want a code that returns = [2,3,5,7,11,13,17,19,23,29]

Note – I understand the range function is an issue since it iterates until that number. However without it my code wont work and I didnt really know how to explain my issue. I originally thought the question I was given was to ask for two inputs (first and last #) and return all prime numbers inbetween. Now I am trying to correct my code for the question at hand (Get N prime #’s)

Asked By: Pedro Rodrigues

||

Answers:

The size of the n-th largest prime pn is < n * (log(n) + log(log(n)) (for n >= 6), which implies pn <= int(n * (log(n) + log(log(n))). Since this is an upper bound we must keep track of the number of primes we’ve generated and stop when we’ve reached n. Here is short python function based on yours illustrating this. It also has an improved upper bound for the inner loop. There are numerous other improvements that are possible.

The upper bound formula only works for n >= 6. You can special-case n < 6 by using [2, 3, 5, 7, 11][:n-1] to get the correct list of primes.

from math import log, sqrt


def calculate_n_prime2(n: int):
    """Only works for n >= 6"""
    upper_bound = int(n * (log(n) + log(log(n))))
    count = 0
    for num in range(2, upper_bound + 1):
        for i in range(2, int(sqrt(num)) + 1):
            if num % i == 0:
                break
        else:
            count += 1
            print(num, end="-")
            if count == n:
                return
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.