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]

Ok, now to read the values... let's recurse that bad boy...

  let rec AddNums n =
      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:

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

Now just to output the result:

  printfn "Result = %A" (AddNums 99)
  let wait = System.Console.ReadLine();

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

Comments on this entry:

Gravatar # re: Euler Problem 13 - F#
by Jason Robinson at 11/21/2014 7:39 PM

Thanks for pointing me in the right direction, as I'm just learning myself, however, for me what worked was 'L' and not 'N'. I'm using F# 3.0 and this is based on their Language reference. http://msdn.microsoft.com/en-us/library/dd233193.aspx

Hope this helps someone else.
Post A Comment
Title:
Name:
Email:
Comment:
Verification: