Sunday, May 23, 2010

Project Euler | Problem 6 (&7!)

Problem 6 is one of those where functional programming just makes things WAY too easy. Look at this:
squares x = [y^2| y<-[1..x]]
answer = (sum ([1..100]))^2 - sum(squares 100)

If you know how list comprehension (the [result | var<-generator;condition] part) works, and you know that [x..y] is all the natural numbers between x and y, including x and y, you can understand the above.
List comprehension works like this:
The generator generates one value. Each occurrence of var is replaced by the value, the conditions, of any, are evaluated, and if all of them apply, result is evaluated and "returned". Since functional languages like these are lazy, evaluation of a list comprehension only occurs when a value from the list is actually needed. Thus, one can define all prime numbers as follows:
allPrimes = [y |y<-[1..];isPrime( y )]
And use it as a list containing all possible primes (assuming the isPrime function exists). Just be sure not to call reverse or something on an infinite list like this. If you try to find the xth prime, all you have to do is allPrimes!x and the list will be evaluated up to the xth result.

[edit]
Holy crap, I almost answered problem 7 without even reading the question. Given allPrimes from above and isPrime from problem 3, we can do:
allPrimes ! 10001

And we're given the prime we want.
[/edit]


By the way, this album is fucking badass:
Ultramagnetic MC's - Critical Beatdown
The Cosmic Hearse, a blog I've followed for nearly a year now, posted this and I've been hooked ever since. Its sound is fairly repetitive, but Kool Keith is just really fucking solid and there are some great samples and beats here. One of the strongest rap albums out there, possibly.

No comments:

Post a Comment