Home > Software design >  Any ways to cut-down this code for printing N amount of prime numbers?
Any ways to cut-down this code for printing N amount of prime numbers?

Time:12-16

I am very new to Python and am playing around with the language. I was tasked with printing the first 20 (or N amount of) prime numbers and played around with it until I found a satisfying solution in my eyes. I'm just wondering if there are some syntax/functions I don't know about to shortcut/cut-down this code? I'd also like some general feedback on what to improve on. Thanks!

def prime_numbers(amount):
    index = 0
    loop = 0
    while index < amount:
        factor = 0
        loop  = 1
        for i in range(1, loop   1):
            if (loop % i) == 0:
                factor  = 1
        if factor == 2:
            index  = 1
            print("#"   str(index)   " is "   str(loop))

prime_numbers(20)

CodePudding user response:

Intiutive variable naming
I think this is proper code. In my opinion, the readability would be improved by more intuitive variable names. Maybe it's just me, but here are my suggesions:

  • n_factors instead of factor. Since this variable denotes an amount and not actually the factor, you can use the prefix n. As far as I'm concerned, this is commonly used.
  • n instead of loop. This variable denotes the number which you are testing to be prime or not. So you should give it a name that says to the reader, "Hey, I am a number". If you don't hesitate to type more for better readability, try possible_prime or something the like.
  • divisor instead of i. I assume that this is my most arguable suggestion, for i is very common to use for iterating. Still I think that a variable should "speak to the reader". Again, the longer possible_divisor is even better (personal opinion).

CodePudding user response:

You don't need to check modulos for all n<k.
Fast and easy way is using square roots( sqrt function from math module). Like this: for i in range(1, math.sqrt(loop 1)): ... Please note that you have to put import math line on the beginning of your code.
NOTE: (loop 1)**(1/2) does also work, but it is a bit less pythonic.

  • Related