grooveplex - 1 year ago 51

Swift Question

**This question contains the solution to Project Euler Problem 1. Stop reading now if you want to figure it out yourself.**

This is the fixed Swift code:

`var s = 0`

for n in 0..<1000 {

if n % 3 == 0 || n % 5 == 0 {

s += n

}

}

print(s)

Result:

`233168`

Try online

I solved Project Euler Problem 1 in Python, so I decided to do the same in Swift as well. But: here's the thing, with identical code I get two different results in Python and Swift.

The answer in Swift is 1000 off (too high). In Python the result is

`233168`

`234168`

`s = 0`

for n in range(0, 1000):

if n % 3 == 0 or n % 5 == 0:

s += n

print(s)

Result:

`233168`

Try it online

`var s = 0`

for n in 0...1000 {

if n % 3 == 0 || n % 5 == 0 {

s += n

}

}

print(s)

Result:

`234168`

Try it online

Answer Source

`Python`

range does not include right end, So the last `1000`

is exactly the difference, and swift range includes the right end! In Python it is done mainly for arrays to do `range(len(some_collection))`

In Python make it `range(1,1001)`

**or** in swift `1...999`

and you'll get the same results.