Created
October 10, 2011 10:27
-
-
Save mattyw/1275005 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes in Dart. It's a first pass and in desperate need of refactoring but it works for now.
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
var expected = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113]; | |
compareLists(lista, listb) { | |
if (lista.length == listb.length) { | |
for(var i = 0; i < lista.length; i ++) { | |
if (lista[i] != listb[i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
else { | |
return false; | |
} | |
} | |
range_of_bools(end) { | |
var ls = []; | |
for (var i = 0; i < end; i++) { | |
print('adding ${i}'); | |
ls.add(true); | |
} | |
return ls; | |
} | |
bool_list_to_integer_list(list) { | |
var ls = []; | |
for(var i = 0; i < list.length; i++) { | |
if (list[i]) { | |
print('${i}'); | |
ls.add(i); | |
} | |
} | |
return ls; | |
} | |
sieve_of_e(n) { | |
var primes = range_of_bools(n); | |
primes[0] = false; | |
primes[1] = false; | |
print('primes ${primes.length}'); | |
for(var p = 2; p < n; p++) { | |
for(var i = p; i < n; i++) { | |
if (p * i < n) { | |
print('falsing ${p*i}'); | |
primes[p * i] = false; | |
print('done'); | |
} | |
} | |
} | |
return primes; | |
} | |
main() { | |
var primes = sieve_of_e(120); | |
if (compareLists(bool_list_to_integer_list(primes), expected)) { | |
print('Sieve is working :) !'); | |
} | |
else { | |
print('Sieve failed :( !'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment