Project Euler Problem 1

Project Euler problem 1 wants a person to find the sum of all numbers less than 1000 that are divisible by 3 and 5. I was able solve this problem pretty easily in Scala. My solution is very similar to how I would solve the problem in Java. Quickly glancing at the code, you can see there is less of it. Keywords in Java like Public and static aren’t in here. It may not see like much, but it adds up.

Using a while loop solved the problem. I have more variations of the solution I will post later. If you are trying to learn a new programming language, projects like Euler is a great way to do this. For now just trust me, I will write a follow up article on why.

To explain my solution, I recast your imperative solution in a functional form. The two mutable variables you used — sum and a — were replaced with a foldLeft and a sequence.

What was a comes from (0 until 1000) — a Seq[Int] that includes the numbers 0 <= i accumulator + reduce(current) }

Which says: Initialize accumulator to 0. Iterate over the numbers for 0 until 1000, updating accumulator as needed.

You can then use Scala’s magic _ syntax sugar to make it more concise. Whenever you’re defining a function whose parameters are known (in this case, the accumulator = accumulator + reduce(current) is actually a function whose type is defined by the foldLeft function), if you use each parameter exactly once, each subsequent use of _ refers to the next parameter.

Please take some time to learn the language before posting these kinds of “solutions”. What you’ve done was just translate a Java solution and say it’s Scala, very very bad coding style. Kim’s solution is how you should be thinking about this in Scala.

I removed the semi-colons. Thank you for your insight. I appreciate your opinion. I feel that posting Java-Scala hybrid solutions help people understand the new concepts in Scala. I never stated use this code in production, or this is “good style.” I stated this is a solution I came up with.