grooveplex - 5 months ago 7x
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?