Sunday, November 24, 2013

Problem 35 - ChucK

ChucK is a programming language that was never intended to be used for Project Euler. It is a"Strongly-timed, concurrent, and On-The-Fly Music Programming Language." Obviously, I did not have to make music to solve this problem, so I used few of ChucK's features. However, it is a programming language, so it is fair game for this challenge. My solution in ChucK to problem 35 has, unfortunately, 25 times as many lines as my previous solution, which was in J (I wanted to use J for problem 69, as will be clear in my next post). Nonetheless, ChucK was a reasonable enough language, even if the chuck operator => is rather odd. Solution runs in about 25s on my machine...not fast, but not Euler-rules-breakingly slow either.
fun int isPrime(int x) {
    if (x < 2) {
        return 0;
    } else if (x % 2 == 0) {
        return x == 2;
    }

    for (3 => int i; i * i <= x; 2+=>i) {
        if (x % i == 0) {
            return 0;
        }
    }
    return 1;
}

fun int mag(int x) {
    if (x < 10) {
        return 1;
    } else {
        return 10 * mag(x/10);
    }
}

fun int rotate(int x) {
    x % 10 => int d;
    return (d * mag(x)) + (x / 10);
}

fun int isCircPrime(int x) {
    if (!isPrime(x)) {
        return 0;
    }
    x => rotate => int r;
    while (x != r) {
        if (!isPrime(r)) {
            return 0;
        }
        r => rotate => r;
    }
    return 1;
}

//main
0 => int ans;
for (0 => int i; i < 1000000; ++i) {
    if (isCircPrime(i)) {
        ++ans;
    }
}
<<<ans>>>;

No comments:

Post a Comment