grooveplex grooveplex - 7 months ago 10
Swift Question

Swift and Python: identical code results in different results

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




Fixed Swift code



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




Original question



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
and in Swift it's
234168
.

Python



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

Swift



var s = 0

for n in 0...1000 {
if n % 3 == 0 || n % 5 == 0 {
s += n
}
}

print(s)


Result:

234168


Try it online




My question is: why is that? What am I doing wrong? How can I fix the Swift code?

Answer

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.