Skip to content Skip to sidebar Skip to footer

How To Add Numbers In A Range

Hey so I'm trying to do a challenge to add every number in multiples of 3 or 5 under 1000, and when I put in this code: for x in xrange(1000): if x % 3 == 0 or x % 5 == 0: plac

Solution 1:

Your issue is you are not retaining any value through each iteration of your loop. Your loop would be fixed with:

place = []
for x in range(1000):
    if x % 3 == 0 or x % 5 == 0:
        place.append(x)
sum(place)

Or just calculated along the way:

result=0for x inrange(1000):
    if x %3==0or x %5==0:
        result+= x
result

As pointed out, a simple generator expression would solve the problem:

sum(x for x inrange(1000) if x % 3 == 0or x % 5 == 0)

Note: I use Py3 - in Py2 xrange() would be an optimisation by avoiding the list construction of range().

But there is a closed form for sum(range(n+1)):

s(n) = n * (n + 1) // 2

e.g.:

sum([0, 1, 2, 3, ..., 999]) == 999 * 1000 // 2 == 499500

Which can be extended to sum(range(0, n+1, c)) as:

s(n,c)=c*(n//c)*(n//c+1)//2

e.g.:

sum([0, 3, 6, 9, ..., 999]) == 3 * (999//3) * (999//3 + 1) // 2 == 166833

So you can rewrite the problem as s(999, 3) + s(999, 5) - s(999, 15), you must subtract s(999, 15) or you double count all the values that are divisible by both 3 and 5, e.g.:

In []:
n = 1000
s = lambda n, c: c  * (n//c) * (n//c + 1) // 2s(n-1, 3) + s(n-1, 5) - s(n-1, 15)

Out[]:
233168

This is O(1) vs O(n) for all the various sum approaches proposed.

Solution 2:

Rather than testing each number between 0 and 1000 to see if it's a multiple of either 3 or 5, then summing those, generate a set that only contains multiples of 3 or 5 between 0 and 1000.

nums = set(range(3, 1000, 3))
nums.update(range(5, 1000, 5))
total = sum(nums)

Much more efficient to just not generate the numbers you don't want in the first place.

(A set is needed because some numbers are multiples of both 3 and 5 and the set will automatically include these only once. Also note our ranges omit 0 entirely since it doesn't affect the sum. Just a tiny bit more efficiency.)

Solution 3:

This is also a great case for list comprehension:

total = sum([x for x in xrange(1000) if x % 3 == 0 or x % 5 == 0])

Edit: It doesn't even need to be a list in this case (and I would imagine more efficient because [correct me if I'm wrong] the summing a generator only traverses the range once whereas the first would traverse the original range, create a range, then traverse it again to get the sum):

total = sum(x for x in xrange(1000) if x % 3 == 0 or x % 5 == 0)

Solution 4:

sum(set(range(0, 1000, 3) + range(0, 1000, 5)))

Create a list of the numbers in the range, stepping by the divisible number, then remove duplicates, sum the result.

Solution 5:

Try this:

total=0for x inxrange(1000):
    if x % 3 == 0or x % 5 == 0:
        total += x

Post a Comment for "How To Add Numbers In A Range"