user2894733
user2894733

Reputation: 11

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.

Upvotes: 0

Views: 911

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213223

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.

Upvotes: 2

Related Questions