Instantly share code, notes, and snippets.

# sblom/Example1.m Created Apr 1, 2012

Lazy list implementation for Mathematica
 (* Project Euler Problem 1 *) (* Find the sum of all the multiples of 3 or 5 below 1000. *) (* StreamSource[#&] is a simple idiom for "a stream of all the natural numbers". *) ints = TakeWhile[StreamSource[# &], # < 1000 &]; (* Choose only the numbers that are multiples of 3 or 5. *) filtered = Select[ints, Mod[#, 3] == 0 || Mod[#, 5] == 0]; (* Sum them. Will probably add Stream/:Total[] since it comes up a lot. *) Fold[Plus, 0, filtered]
 (* Project Euler Problem 2 *) (* By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. *) (* Create a stream of Fibonacci numbers. *) fibo = StreamSource[Fibonacci]; (* Use TakeWhile to get all the numbers under 4 million, and then filter for evenness. *) filtered = fibo ~TakeWhile~ (#<4000000&) ~Select~ EvenQ; (* Total them up. *) Fold[Plus, 0, filtered]
 (* Project Euler Problem 10 *) (* Find the sum of all the primes below two million. *) (* Create a stream of Prime numbers. *) primes = StreamSource[Prime]; (* Sum the ones under 2 million. *) Fold[Plus, 0, Select[primes, #<2000000&]]