简体   繁体   中英

How to find a program that will add the sums of numbers that are divisible by only certain numbers

Sorry, I am new to Python. I want to find a Python program that will find the sum of integers 1 to n that are divisible by a and b but not by c.

For example, if

n = 20, a = 3, b = 4 and c = 5 

we would have:

3 + 4 + 6 + 8 + 9 + 12 + 16 

The code I have right now is something like:

   def summing(n):
        x = sum(k for k in xrange(n) if (k%3==0) or (k%4==0))
        return x - sum(k for k in xrange(n) if (k%5==0))

But, I know this isn't right because it subtracts multiples of 5 even if they aren't divisible by 3 or 4.

def sumNumInRange(n):
    return sum(k for k in xrange(n) if k % 5 != 0 and (k % 3 == 0 or k % 4 == 0))

Also consider not to hardcode values like 3 , 4 and 5 . It might be better to pass those as arguments to function.

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