Created
January 7, 2016 18:38
-
-
Save giwa/011150c4cdb94c246dfd to your computer and use it in GitHub Desktop.
Prime number ref: http://qiita.com/giwa/items/4f886c37170c5cc863c7
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
import math | |
""" | |
Given list of integer and find primes | |
""" | |
l = list(range(1, 101)) | |
def is_prime(x): | |
if x == 1: | |
return False | |
upper_limit = int(math.sqrt(x)) + 1 | |
for i in range(2, upper_limit): | |
if x % i == 0: | |
return False | |
return True | |
primes = [] | |
for i in l: | |
if is_prime(i): | |
primes.append(i) | |
print(primes) | |
""" | |
Given integer and find primes which are less than the integer | |
""" | |
n = 101 | |
if n > 2: | |
# it is not necessary to check all number which is less than the integer | |
# create list of odd integer | |
l = list(range(3, n, 2)) | |
# 2 is the minimum prime | |
primes = [2] | |
for i in l: | |
f = False | |
for j in primes: | |
# Compare upto sqrt(i) then if there have not been any numbeer | |
# which can divide i, i is prime | |
if j * j > i: | |
f = True | |
break | |
if i % j == 0: | |
break | |
if f: | |
primes.append(i) | |
print(primes) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment