DEV Community

Deniz
Deniz

Posted on

Project Euler #001 in Python: Multiples of 3 or 5

Problem

Project Euler Problem #001 asks us to find the sum of all natural numbers below 1000 that are multiples of 3 or 5.

Problem link:

https://projecteuler.net/problem=1

This is a great beginner-friendly problem because it teaches one of the most important ideas in programming:

Check every number, apply a condition, and accumulate the result.


Idea

A number should be added to the total if it is divisible by 3 or 5.

In Python, divisibility can be checked with the modulo operator:

n % 3 == 0

Enter fullscreen mode Exit fullscreen mode

This means:

n leaves no remainder when divided by 3.

So the condition becomes:

n % 3 == 0 or n % 5 == 0
Enter fullscreen mode Exit fullscreen mode

Python solution

total = 0

for n in range(1000):
    if n % 3 == 0 or n % 5 == 0:
        total += n

print(total)
Enter fullscreen mode Exit fullscreen mode

Explanation

We start with:

total = 0
Enter fullscreen mode Exit fullscreen mode

Then we loop through every number below 1000:

for n in range(1000):
Enter fullscreen mode Exit fullscreen mode

For each number, we check whether it is a multiple of 3 or 5:

if n % 3 == 0 or n % 5 == 0:
Enter fullscreen mode Exit fullscreen mode

If the condition is true, we add that number to the total:

total += n
Enter fullscreen mode Exit fullscreen mode

The final answer is:

233168
Enter fullscreen mode Exit fullscreen mode

Complexity

Time complexity: O(n)

Space complexity: O(1)

This solution checks each number once and only keeps one running total.


Visual explanation

I also made a short visual version of this solution as part of my EulerCodeLab series:

▶️ YouTube Short:


Source code

GitHub:

https://github.com/denizguneey/eulercodelab-data/tree/main/project-euler/001


Final note

I’m building a daily Project Euler with Python visual series.

Each problem includes:

  • a short Python solution
  • a visual explanation
  • a GitHub source code link
  • a beginner-friendly breakdown

More problems are coming soon.

Top comments (0)