Project Euler #1 - are we fizz-buzzing?

fangcode

Łukasz Kiełczykowski

Posted on December 27, 2022

Project Euler #1 - are we fizz-buzzing?

Disclaimer

This blogpost provides solution to the first problem from Project Euler. If
you want to figure out a solution yourself, go to the
Problem 1's page and come back later :)

This is going to be a very brief post as the problem is very simple as well.
It's similar to pretty well known FizzBuzz problem, which is a basic
recruiting task or a simple task at the beginning of one's programming-learning journey.

The Problem

If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

The simplest O(n) solution would be iteration over the numbers and find multiples of 3 and 5.

Solution

The simplest solution using a loop would like something like this:

private fun loopApproach(input: Int): Int {
    var acc = 0
    for (i in 3 until input) {
        if (i.mod(3) == 0 || i.mod(5) == 0) {
            acc += i
        }
    }

    return acc
}
Enter fullscreen mode Exit fullscreen mode

To be more kotlin you could use fold instead of usual for-loop:

private fun foldApproach(input: Int): Int =
    (3 until input).fold(0) { acc, value ->
        if (value.mod(3) == 0 || value.mod(5) == 0) {
            acc + value
        } else {
            acc
        }
    }
Enter fullscreen mode Exit fullscreen mode

The fold, however, is a bit slower. With large input value
(1_000_000_000 instead of 1_000 and I need use Long for that) which takes in both cases almost 3 seconds on my computer, the difference is over
100ms.

Conclusion

The simplest problem is done. Let's move on to the next and let's see what we can get out of it.

Thank you for your time and see you in the next one!

💖 💪 🙅 🚩
fangcode
Łukasz Kiełczykowski

Posted on December 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related