How to Sum Numbers Divisible by 5 in Python

0
6
Asked By CodeMaster2023 On

I'm trying to solve a Python problem where I need to use a while loop to calculate the total of numbers between 1 and n (inclusive) that are divisible by 5. I also need to keep track of how many numbers meet this criteria and store the results in 'count' and 'res'. For example, if n is 18, I expect the count to be 3 and the sum to be 30. Any advice on how to approach this would be great!

3 Answers

Answered By TechWhizKid On

It looks like you're asking about how to implement this using a while loop. A simple way to do it would be to start with a count and a result variable initialized to zero. Then use a while loop to iterate through the numbers until you reach n, checking if each one is divisible by 5. Here's a rough example:

```python
n = 18
count = 0
res = 0

for x in range(1, n + 1):
if x % 5 == 0:
count += 1
res += x

print("count", count)
print("res", res)
```
This should give you what you need! The modulo operator checks for divisibility, returning 0 if it's a multiple of 5.

Answered By LambdaLover88 On

You can also use a lambda function for a more compact solution! Check this out:

```python
count_divisible = lambda n=18, divisor=5: (len(divisibles:={i for i in range(1, n+1) if i % divisor == 0}), sum(divisibles))

count, res = count_divisible(18, 5)
```
This returns count as 3 and res as 30, just like you wanted!

Answered By PythonNinja99 On

Have you tried sharing your code? It helps others understand what you’re working with. But just a heads up, there’s actually a community specifically for learning Python that might be better suited for your question.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.