Logic
Logic

Reputation: 63

It seems my code skips a part for no clear reason

I wrote the code below to print out multiples of 3 and 5 in a range of numbers from 1 - 100 but it seems that I only keep on getting the multiples of 3 only.

counter = 1
for i in range(1, 101):
    if 3 * counter == i:
        print(i)
        counter += 1
    elif 5 * counter == i:
        print(i)
        counter += 1

Can someone help me figure out the issue.

Upvotes: 0

Views: 56

Answers (4)

Chris
Chris

Reputation: 36621

Let's look at what happens as this executes.

counter = 1
i = 1
3 * counter = 3
5 * counter = 5

counter = 1
i = 2
3 * counter = 3
5 * counter = 5

counter = 1
i = 3
3 * counter = 3
printed: 3
counter += 1

counter = 2
i = 4
3 * counter = 6
5 * counter = 10

counter = 2
i = 5
3 * counter = 6
5 * counter = 10

counter = 2
i = 6
3 * counter = 6
printed: 6
counter += 1

If you want all multiples of 3 and 5, you want to use the modulo operator (%).

count = 0

for i in range(1, 101):
    if i % 3 == 0 or i % 5 == 0:
        print(i)
        count += 1

print(f"counted: {count}")

Upvotes: 2

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4137

I would try something like this:

for i in range(1, 101):
    if (0 in [i%3, i%5]):
        print(i)

The % operator is called the modulo operator, and returns the remainder of the given division.

>>> 4 % 2
0
>>> 4 % 3
1
>>> 3 % 4
3

In your case, since you are searching for numbers that are multiples of 3 or 5, this operator is what you need.

Upvotes: 1

Martin Wettstein
Martin Wettstein

Reputation: 2894

Your program can not work. When i==3, the counter will be increased to 2, when i==6, counter will be increased to 3, and so on. The counter may never be lower than a third of i, therefore it will never be a fifth of i.

So, if you want to stick with the idea of the counter, you need two counters. One for fifths, the other for thirds:

counter3 = 1
counter5 = 1
for i in range(1, 101):
    if (3 * counter3) == i:
        print(i)
        counter3 += 1
    if 5 * counter5 == i:
        print(i)
        counter5 += 1

But there are much more elegant ways to find numbers divisible by 3 and 5.

Upvotes: 0

Helios
Helios

Reputation: 715

You are solving Project Euler #1? Since this is the first question I will help, but in general posting the entire question will ruin the fun, if you are stuck post the specific part you need help on.

You do not want to test your counter, since you are basically keeping track of what 3 (the smallest value) should be divided by to get that number.

counter = 1

for i in range(1, 101):
    if i % 3 == 0:
        print(i)
        counter += 1
    if i % 5 == 0:
        print(i)
        counter += 1

print(f"counted: {counter}")

Upvotes: 0

Related Questions