Skip to content

Instantly share code, notes, and snippets.

@canxerian
Created August 23, 2012 00:45
Show Gist options
  • Save canxerian/3430904 to your computer and use it in GitHub Desktop.
Save canxerian/3430904 to your computer and use it in GitHub Desktop.
A python function to return primes from 2 to n
def get_primes(n) :
# 2 is the smallest prime. Declaring it here cleans up the algorithm
primes = [2];
# Start calulating primes at 3
prime_count = 3;
while prime_count <= n:
# can it be divided by
to_be_divided_by = prime_count - 1
while to_be_divided_by > 1:
# if the current number is divisible by a value between itself and 1 (exclusive), it's not a prime
if prime_count % to_be_divided_by == 0:
break
else:
to_be_divided_by -= 1
if(to_be_divided_by == 1):
primes.append(prime_count)
break
prime_count += 1
return primes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment