Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project euler #1. I keep getting the answer wrong by exactly 100 and I don't know why (written inF#)

I'm a first year CS student, with no prior knowledge in programming. I was recommended to go through the problems of Project Euler, and have managed to solve (almost) the first problem.

It states that you have to sum all the numbers which is a multiple of either 3 or 5 (or both).

My code in F#:

let mutable n = 0
for i in 0..1000 do
  if (i % 3 = 0) || (i % 5 = 0) then
    n <- i + n

printfn "%A" n

When this is run, I get answer 234168 which is off by 100 of the real answer.
Any suggestion why?

like image 620
VanTheMan Avatar asked Nov 08 '22 04:11

VanTheMan


1 Answers

Posting an answer to this question to make it easier for others to learn from the mistake.

let mutable n = 0
for i in 0..999 do
  if (i % 3 = 0) || (i % 5 = 0) then
    n <- i + n

printfn "%A" n

Credit should go to JJJ for giving the original hint and Guy Coder for pointing out that a more functional approach would be more idiomatic in F#.

like image 129
jpierson Avatar answered Dec 09 '22 15:12

jpierson