#### Euler Problem 13 - F#

I finally managed to solve a Euler problem in F# without first resorting to a C# version... That problem? 13...

The problem is:

"Work out the first ten digits of the sum of the following one-hundred 50-digit numbers."
//Numbers all here...

Usually, I go for the C# approach first, then see how I can work that into F#, but seeing as I didn't have any 'BigNum' types in C# (and I didn't consider the fact that I only needed to add the first 11 digits of each number - doh!) I dove straight into F#'s 'BigNum' type.

The first issue I had was actually how to define a BigNum.
First, I tried:

let x = 37107287533902102798797998220837590246510135740250

But that gives me an error:
"This number is outside the allowable range for 32-bit signed integers."

I had to do a bit of googling before finding that adding the letter 'N' to the end of the number defines it as a BigNum, so:
let x = 37107287533902102798797998220837590246510135740250N

works fine.

A quick test:

let x = 37107287533902102798797998220837590246510135740250N
let y = 46376937677490009712648124896970078050417018260538N
let z = x + y
printfn "z= %A" z

Good good, seems to work.

Next step was to define the values, for which I used a list:

let bigNums = [37107287533902102798797998220837590246510135740250N;
46376937677490009712648124896970078050417018260538N;
//... The rest of the numbers ...//
53503534226472524250874054075591789781264330331690N]

if n < 0 then 0 else AddNums (n-1) + bigNums.[n]

Err... error???
"Type constraint mismatch. The type   int is not compatible with type  Math.BigNum. The type 'int' is not compatible with the type 'Math.BigNum'."

Um, Not sure what's the problem here.... ahhh now I see it...
bigNums is a list of BigNum type, and I add two BigNum's together all the way until n < 0. At this point I'm returning an Int. If I change that to 0N, the it's returning a BigNum as well.. so.. final function is:

if n < 0 then 0N else AddNums (n-1) + bigNums.[n]

Now just to output the result:

printfn "Result = %A" (AddNums 99)

We use '99' as the value as that's the top of the bigNums array.

Aces!

Print | posted @ Friday, January 23, 2009 12:07 PM # re: Euler Problem 13 - F#