Created
August 23, 2012 00:45
-
-
Save canxerian/3430904 to your computer and use it in GitHub Desktop.
A python function to return primes from 2 to n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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