Prime sieve
Tuesday, December 11th, 2007Since I haven’t posted in ages, and D doesn’t get nearly enough love from anyone, have a prime sieve.
This is public domain, I suppose. It’s not very spectacular, and took maybe ten minutes to write, so whatever.
module sieve; import fun; long[] sieveTo(long lim) { long l = 0; long[] o; o.length = 100; foreach (ref i; o) i = 2; for (long i = 2; i < lim; i++) { if (!o.any( (long p) { return i != 0 && i % p == 0; } )) { if (l >= o.length) o.extend(); o[l++] = i; } } o.length = l; return o; } private void extend(T)(ref T[] arr) { int l = arr.length; arr.length = arr.length * 2; for (int i = l+1; i < arr.length; ++i) arr[i] = 2; }
the relevant part of fun.d (where I reimplement the parts of Haskell I miss :v ) is the any function:
bool any(T)(in T[] arr, bool delegate(T) p) { foreach(t; arr) if (p(t)) return true; return false; }
All in all, D is surprisingly concise, and nice, and people should use it more.
And it should have Qt bindings for it.

