A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Saturday, September 12, 2009

Project Euler, Problem 1

Problem 1 for Project Euler was to "Add all the natural numbers below one thousand that are multiples of 3 or 5." Logically, it's a simple enough problem: for each number between 3 and 999, if it is evenly divisible by 3 or 5, we will need to put in our running total. The challenge for me is getting into the whole mindset of functional programming. I can't wait to compare this first solution to what I'll hopefully be writing in a few months.


open System
// open Microsoft.FSharp.Collections.Set

// If we list all the natural numbers below 10 that are
// multiples of 3 or 5, we get 3, 5, 6 and 9.
// The sum of these multiples is 23.
// Find the sum of all the multiples of 3 or 5 below 1000.

let rec threeMultiples n =
if n = 3 then [3]
else if n % 3 = 0 then threeMultiples(n-1) @ [n]
else threeMultiples(n-1)

let rec fiveMultiples n =
if n = 5 then [5]
else if n % 5 = 0 then fiveMultiples(n-1) @ [n]
else fiveMultiples(n-1)

// Define the upper limit of where we are looking
let ceiling = 1000 - 1

// generate a list of all the natural numbers less than ceiling
// evenly divisible by 3 or 5.
// TODO: Understand how to pass 2 params to recursive fxn
let tempList = threeMultiples ceiling @ fiveMultiples ceiling

// Convert our list to a set to eliminate the duplicate values
let setList = Set.of_list tempList

// Convert the set back to a list so we can accumulate them
let sumList = Set.to_list setList

// Sum them numbers up
// You//s a big fine function,
// won//t you sum them numbers up
// Original lyrics by Juvenile (1999)
// Insipid comments like the above are why I should be sleeping
let sums = List.sum sumList

System.Console.WriteLine(String.Format("Sum of the natural numbers divisible by 3 and 5 under {0} is {1}", ceiling, sums))

Now I can sleep

No comments: