Home Contact

X

Coder, not artist.

News

Current archive is at: http://cskardon.wordpress.com/ - I aim to move it all soon! All code on here is free, but as a consequence it's up to you to check it, ha! If you have any questions, feel free to email: cskardon -- @ -- xclave dot co dot uk I'm sure you can decrypt the address there!

Twitter












Archives

Post Categories

Image Galleries

Syndication:

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!

Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: