+ 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

22nd Aug 2022, 4:03 PM
Sonja
14 Respostas
+ 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)
22nd Aug 2022, 7:17 PM
Lothar
Lothar - avatar
+ 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.
27th Feb 2023, 8:17 PM
Lothar
Lothar - avatar
+ 4
GERAKULES Read the task description carefully: If the number is divisible by 3 as well 5, it should be counted only once.
26th Feb 2023, 5:07 PM
Lisa
Lisa - avatar
+ 3
You could use the filter function for example https://code.sololearn.com/c1UO6j8pcwNG/?ref=app
22nd Aug 2022, 4:20 PM
Lisa
Lisa - avatar
22nd Aug 2022, 4:25 PM
AÍąJ
AÍąJ - avatar
+ 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...?
22nd Aug 2022, 4:28 PM
Lisa
Lisa - avatar
+ 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))
22nd Aug 2022, 4:29 PM
Bob_Li
Bob_Li - avatar
+ 2
My 15 pence: s =sum( [n for n in range(15 ) if n%3*n%5==0])
22nd Aug 2022, 7:00 PM
Oma Falk
Oma Falk - avatar
+ 1
Lisa Yes so there should be i % 15 == 0: But output will be same in both case
22nd Aug 2022, 4:36 PM
AÍąJ
AÍąJ - avatar
+ 1
Lothar Is it a sololearn task? The task description in the thread read to me like "all numbers < input number"
22nd Aug 2022, 7:23 PM
Lisa
Lisa - avatar
+ 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)
26th Feb 2023, 5:01 PM
GERAKULES
GERAKULES - avatar
+ 1
Thank you, Lothar for explanation.
27th Feb 2023, 8:52 PM
GERAKULES
GERAKULES - avatar
0
Help me please. It doesn't work. Why? https://code.sololearn.com/cYKdqQiXQw2k/?ref=app
26th Feb 2023, 5:04 PM
GERAKULES
GERAKULES - avatar
0
Thank you, Lisa! :)
26th Feb 2023, 5:19 PM
GERAKULES
GERAKULES - avatar