简体   繁体   中英

Sum all numbers 0 to x that are divisible by y using while loop in python

I need to write a script using a while loop (not using the for function whatsoever) to sum all numbers between 0 and x that are divisible by div1. This is what I have.

def sum_upto_divisible(x,div1):
    i=0
    while i<x:
        i+=1
        if i%div1==0:
            i+=i
    return(i)

If x = 25 and div1=5, the answer should be 50. My current loop gives me an answer of 30. I understand that the loop is adding until 5, then doubling it. Then it returns to adding 1 to i (now 10) until it hits 15. Then it doubles 15 and the loop ceases. I need to add 5, 10, 15, and 20. How can I fix the loop I have now?

def sum_upto_divisible(x,div1):
    if div1 < 0 :
        div1 = -div1
    i=0
    s=0
    while i < x:
        s += i
        i += div1
    return s
def sum_upto_divisible(x, div1):
    return sum([num for num in x if num % div1 == 0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM