1
import time
start_time = time.time()
a = [2]
inp = 2
while inp < 60000:
    div = 2
    inp += 1
    while div <= (inp / 2 + 1):
        prime = inp / div
        if prime.is_integer() == True:
            break
        else:
            if div >= (inp / 2):
                a.append(str(inp))
                break
            else:
                div += 1

print(a)
print(len(a))
print("Process finished --- %s seconds ---" % (time.time()-start_time))

I wrote my first own program to calculate every prime number between 0 and 60000. I am searching for tips how to format it better or improve it.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Hey, your question might be better suited for https://codereview.stackexchange.com/. Your writing style is fine, I'd just put it in a function and add some comments. – Peter Aug 04 '21 at 13:06
  • 1
    You could implement a [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_and_variants), of which there are [many examples](https://stackoverflow.com/q/49936222/10077) [on Stack Overflow](https://stackoverflow.com/q/3939660/10077). – Fred Larson Aug 04 '21 at 13:07

2 Answers2

0

this is how i would have done it

def isPrime(n) :
    if (n <= 1) :
        return False
    if (n <= 3) :
        return True
    if (n % 2 == 0 or n % 3 == 0) :
        return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

def printPrime(n):
    for i in range(2, n + 1):
        if isPrime(i):
            print (i, end =" ")

n = 60000  <--- you can change n by any value you want        
printPrime(n)
  • if you want to make it even shorter you can remove the first 3 ifs but then you don't have any error handling so I would suggest leaving them just in case – matthew fabrie Aug 04 '21 at 13:09
  • your code was pretty much fine but I would suggest adding a function for everything you do so that you can call that function when you need and it does not always get executed. Other than that it's good – matthew fabrie Aug 04 '21 at 13:12
0
import math
n = 60000
primes = []
for k in range(2,n):
    if k % 2 == 0 and k > 2: 
        pass
    elif all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
        print(k)

EDIT

Since even number are not prime except 2, i have modified the anwer again

import math
primes2 = [2]
for k in range(3,n,2):
    if all(k % i for i in range(3, int(math.sqrt(k)) + 1, 2)):
        primes2.append(k)

Or Liner (It will helps in perforamce as well)

from math import sqrt # Most efficient way to use external libraries
primes = [k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))]
primes.insert(0, 2)
# To print
print(*[k for k in range(3,n+1,2) if all(k % i for i in range(3, int(sqrt(k)) + 1, 2))],sep='\n')
Rinshan Kolayil
  • 1,111
  • 1
  • 9
  • 14