sum of n first numbers = n*(n+1)/2
sum of n first multiples of x = x*n*(n+1)/2

there are 333 multiples of 3 < 1000 (last one is 333 * 3 = 999)
there are 199 multiples of 5 < 1000 (last one is 199 * 5 = 995)
there are 66 multiples of 15 < 1000 (last one is 66 * 15 = 990)

I know that many people with coding skills will try to brute-force every project-euler problems… but some of those problems actually don’t need to be brute-forced.

The one liner that most people eventually come up with will be something like:

1

(1 until 1000).filter(x => x%3==0|| x%5==0).sum

or

1

1 until 1000 filter { x => x %3==0|| x %5==0} sum

Kim, a commenter from my first post provided the second one. Thanks!
Below is another revision of the code I came up with. This one is taking input from the command line and using a parallel collection to solve this problem. It runs very fast compared to a large ceiling (i.e. 1,000,000).

The solution I listed above is very verbose. However, I did this for a reason. Most will consider this a Java-Scala hybrid. To me its still Scala; just more readable for new users. I came up with this solution to allow for additional factors. If you wanted to find the sum of the factors 3,5, and 7 for numbers under 1000, you can run the following command.

scala Euler001a 1000 3 5 7

Colin Dellow came up with this. Its very similar to my solution but more concise.

I really appreciate the feedback good and bad. I feel I found a couple of people that care about Scala as much as I do. A good community will always help when learning anything. I have an Actor example I will post next; closing out the series on problem 1.

2 Comments

Not sure if you’ll post this on reddit, but you’ll want to check out List head/tail. That will eliminate your usage of args(0) and argList.slice. ceiling is equivalent to argList.head, while factors becomes argList.tail.map(s=> s.toLong)