Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to write a code that will take user input for N which is the total number of prime numbers to print out. I have executed the below code, but the output is wrong:

#For example, the user enters the value of N = 7.

#Desired output: 2, 3, 5, 7, 11, 13, 19

#Actual output: 2, 3, 5, 7

#Kindly advise.

i = 1

x = int(input("Enter the number:"))

for k in range(1, x+1):

    c = 0

    for j in range(1, i+1):

        a = i % j

        if a == 0:

            c = c + 1

    if c == 2:

        print(i)

    else:

        k = k - 1

    i = i + 1

1 Answer

0 votes
by (108k points)

Simply you can use a regexp in Python:

#!/usr/bin/python

import re, sys

def isPrime(n):

        return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None

N = int(sys.argv[1]) # number of primes wanted (from command-line)

M = 100              # upper-bound of search space

l = list()           # result list

while len(l) < N:

    l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l

    M += 100                                # increment upper-bound

print l[:N] # print result list limited to N elements

Related questions

0 votes
1 answer
asked Jan 5, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 15, 2020 in Python by ashely (50.2k points)

Browse Categories

...