+ 2

Printing prime numbers

if i input 5 how do i make the output to be 2 3 5 7 11?

27th Feb 2017, 11:32 AM
Kanra
Kanra - avatar
2 Réponses
+ 4
""" Improved and optimized version of @StarLord code: for 10000 prime numbers, takes around 20s instead more than 2mn otherwise, in same context... meaning also at first running call for the above version, which will benefits from storing previous founded primes on calling function next times ^^ """ import math primes = [2] # need at least to be initializated with one prime value def is_prime(x): global primes if x == 0 or x == 1: return False if x in primes: return True srx = math.sqrt(x) p = 0 for p in primes: if p > srx: primes.append(x) return True if x % p == 0: return False for y in range(p+1,round(srx)): if is_prime(y): primes.append(y) if x % y == 0: return False return True while True: try: i = int(input("How many prime numbers ( none for exit )? ")) except: break if i == 0: break count = len(primes) if i <= count: print('\n'.join([str(x) for x in primes[:i]])) else: print('\n'.join([str(x) for x in primes])) if count != 0: number = primes[-1] + 1 else: number = 2 while count < i: if is_prime(number): print(number) count += 1 number += 1
28th Feb 2017, 11:07 AM
visph
visph - avatar