+ 1
Multiples
Hi, Given an integer number, output the sum of all the multiples of 3 and 5 below that number. If a number is a multiple of both, 3 and 5, it should appear in the sum only once. I actually solved the task, although there are probably better solutions. I tried to make the code more efficient with the else break but then the last test case fails. Why? https://code.sololearn.com/cvFxl7Hx7GEA/?ref=app
14 odpowiedzi
+ 6
my try, a very basic version:
limit = int(input())
res = 0
for num in range(1, limit):
if num % 3 == 0 or num % 5 == 0:
res += num
print(res)
+ 8
GERAKULES
we do not need to run multiple *for loops*. just use one.
for ...
then use an if... elif... conditional
> check if number from the range is divisible evenly by 3
if yes: add number to s
> check if number from the range is divisible evenly by 5
if yes: add number to s
the issue in your code is, that a number like 15 is divisible by 3 and by 5, so both are added to the sum, since you run 2 loops.
+ 4
GERAKULES Read the task description carefully: If the number is divisible by 3 as well 5, it should be counted only once.
+ 3
You could use the filter function for example
https://code.sololearn.com/c1UO6j8pcwNG/?ref=app
+ 2
Sonja
What about to this logic?
https://code.sololearn.com/c67652sosUua/?ref=app
+ 2
A͢J What is your if-condition supposed to do? If a number is divisible by 3 AND 5, it is also divisible by 3 OR 5...?
+ 2
Sonja
avoid using 'sum' as variable name. It is a python built-in method name and gave me a puzzling error when I tried to code an alternative solution beneath your code...😅
how about this?
num = int(input())
factors = []
for n in range(num):
if n%3==0:
factors.append(n)
elif n%5==0 and n not in factors:
factors.append(n)
#print(factors)
print(sum(factors))
+ 2
My 15 pence:
s =sum( [n for n in range(15 ) if n%3*n%5==0])
+ 1
Lisa
Yes so there should be i % 15 == 0:
But output will be same in both case
+ 1
Lothar Is it a sololearn task? The task description in the thread read to me like "all numbers < input number"
+ 1
Hi, guys! Explain to me what is wrong with this code? Please!
num = int(input())
s =0
for i in range(num):
a = i % 3
if a == 0:
s += i
for j in range(num):
b = j % 5
if b == 0:
s += j
print(s)
+ 1
Thank you, Lothar for explanation.
0
Help me please. It doesn't work. Why?
https://code.sololearn.com/cYKdqQiXQw2k/?ref=app
0
Thank you, Lisa! :)