Archive for the ‘Maths’ Category

Prime sieve

Tuesday, December 11th, 2007

Since 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. :(

Project Euler, bash version

Sunday, October 28th, 2007

OK, so when I’m bored I sometimes attack a few of the problems on Project Euler; so far I’ve done about 40-odd because I’m slow and inept. I just finished problem 41, which is to find the highest pandigital1 number that is prime. I did my program in Haskell, of course, but in the thread someone had this:

primes 1234567 7654321 | grep 1 | grep 2 | grep 3 \
  | grep 4 | grep 5 | grep 6 | grep 7 | tail -n 1

I don’t think I need to tell you that this is the best answer ever. And it’s far faster than mine…


  1. The Wikipedia definition seems to allow multiple occurrences of the same digit; obviously PE didn’t (otherwise there would be infinitely many and thus no ‘largest’). Also, you were allowed numbers less than 123456789 as long as an n-digit number had all the digits 1–n, for example 4231. Which is good since the answer had seven digits. 

Maple

Wednesday, October 17th, 2007

After some annoyance, and coughing up £151, I now have Maple on here to play around with. And to do maths microlab exercises, of course.

As much as the weird syntax (and Swing GUI) is annoying, it’s still fun to play around with. Being able to right-click an equation and integrate, differentiate, solve, or do whatever else to it is the most wonderful thing ever.

Since I don’t really know my way around it2 I can’t really say much about it yet, but yay, new toy.

Image from Wikipedia, taken by this guy. It’s cc-by-sa.


  1. Which is of course better than having to pay about £50, but still. 

  2. There were six microlab sessions last year which took about half an hour each, and that’s the only exposure I’ve had to it.