Add up all the numbers below n that are multiples of 3 or 5.
What to build
A loop that keeps two running values at once.
Requirements
- Read
n. - Consider the numbers from 1 to
n - 1. - Print
count C sum Sfor those divisible by 3 or by 5.
Input
One whole number n.
Output
One line, as in the example.
Constraints
n is from 1 to 100000.
Example
Input:
10
Output:
count 4 sum 23
Why it works
A number divisible by both 3 and 5, such as 15, passes the or test once, so it is only counted once. Two separate if statements would count it twice.
Examples
Example 1 · Input
10
Expected output
count 4 sum 23
Example 2 · Input
16
Expected output
count 7 sum 60
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Loop over every number below n.
Hint 2
Use or to test for either multiple.
Hint 3
Keep a count and a sum, updated in the same if block.
Solution
Show one correct solution (try it yourself first)
n = int(input())
count = 0
total = 0
for i in range(1, n):
if i % 3 == 0 or i % 5 == 0:
count += 1
total += i
print("count", count, "sum", total)