Skip to content Skip to sidebar Skip to footer

Sum Of All Numbers Within A Range Without Numbers Divisible By X In Python

I am trying to make a code (in python) where I can input a range and it will find the sum off all the numbers besides the ones that are divisible by x (which i also choose). For ex

Solution 1:

For your second example: (0<N<5, x=2):

sum(i for i in range(1, 5) if i%2)

Solution 2:

def fn(N, x):
    total =0for i in range(N):
        if i%x:
            total += i
    return total

Read up on loops and ranges in python if you are new.

Solution 3:

You could do something like this:

>>>div = 3>>>n = 10>>>num_div = filter(lambda x: x%div, range(n))>>>sum(num_div)
27

or as a function

deffunc(n,div):
   returnsum(filter(lambda x: x%div, range(n))

Solution 4:

The other answers implicitly assume the range will always start from 0. If you want to be able to set both the start and end points of your range, you could use:

defsumrange(start, stop, n):
    returnsum(i for i inrange(start, stop) if i%n)

Post a Comment for "Sum Of All Numbers Within A Range Without Numbers Divisible By X In Python"