I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime n
Whilst playing with prime numbers in Python V3 I noticed that the smallest number by which a composite(non-prime) number is divisible is itself always a prime that is less than the square root of the number under test.
Below is my implementation of that finding to calculate the first N prime numbers.
first 1,000 primes in 0.028S | first 10,000 primes in 0.6S | first 100,000 primes in 14.3S
The snippet below also indicates how long the generation took and prints out the primes in a nice table format.
import time
import math
def first_n_Primes(n):
number_under_test = 4
primes = [2,3]
while len(primes) < n:
check = False
for prime in primes:
if prime > math.sqrt(number_under_test) : break
if number_under_test % prime == 0:
check = True
break
if not check:
for counter in range(primes[len(primes)-1],number_under_test-1,2):
if number_under_test % counter == 0:
check = True
break
if not check:
primes.append(number_under_test)
number_under_test+=1
return primes
start_time = time.time()
data = first_n_Primes(1000)
end_time = time.time()
i = 1
while i < len(data)+1:
print('{0: <9}'.format(str(data[i-1])), end="")
if i%10 == 0: print("")
i+=1
print("\nFirst %d primes took %s seconds ---" % (len(data),end_time - start_time))