Last active
August 29, 2015 14:05
-
-
Save jxnl/7ea1087cbdeb27c80954 to your computer and use it in GitHub Desktop.
Primes
This file contains hidden or 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
| """ This module contains the following algorithms for generating primes: | |
| - Sieves of Eratosthenes (Optimized) | |
| - Sieve of Atkins | |
| """ | |
| from math import sqrt | |
| def eratosthenes(lim=100): | |
| """ | |
| Implements a Genuine Sieve of Eratosthenes for primes < lim | |
| returns: list of primes < lim | |
| """ | |
| is_prime = list(True for _ in range(lim + 1)) | |
| sqrtn = int(round(sqrt(lim))) | |
| for i in range(2, sqrtn + 1): | |
| if is_prime[i]: | |
| for j in range(i ** 2, lim + 1, i): | |
| is_prime[j] = False | |
| return [i for i, b in enumerate(is_prime) if b and i >= 2] | |
| print(eratosthenes(10000)) |
This file contains hidden or 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
| public class Sieve{ | |
| public static void main(String[] args){ | |
| Integer maxPrime = 10000; | |
| Double sqrtMaxPrime = Math.sqrt(maxPrime); | |
| Boolean[] isPrime = new Boolean[maxPrime+1]; | |
| for (int i=0; i<=maxPrime; i++) { | |
| isPrime[i] = true; | |
| } | |
| for (int i=2; i<=sqrtMaxPrime; i++){ | |
| if (isPrime[i]){ | |
| for (int j=i*i; j<=maxPrime; j+= i){ | |
| isPrime[j] = false; | |
| } | |
| } | |
| } | |
| for (int i=2; i<=maxPrime; i++){ | |
| if(isPrime[i]){ | |
| System.out.println(i); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment