DEV Community

Łukasz Kiełczykowski
Łukasz Kiełczykowski

Posted on

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!

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay