Reputation: 115
Why does the following function return the integer 2000 even though it is not divisible by numbers 3, 6, 7, 9?
var counter = 1000
func divisibleByAllTenNumbers() -> Int{
for _ in 1...counter {
if counter % 2 == 0 && counter % 3 == 0 &&
counter % 4 == 0 && counter % 5 == 0 &&
counter % 6 == 0 && counter % 7 == 0 &&
counter % 8 == 0 && counter % 9 == 0 &&
counter % 10 == 0 {
break
}
else {
counter = counter + 1
}
}
return counter
}
2000 is shown as output even though the expected number was 2520.
What is the possible reason?
Upvotes: 0
Views: 73
Reputation: 318874
You have a confusing use of counter
. It starts at 1000 so the for
loop iterates 1000 times (1...1000). But counter
get incremented from 1000 to 1999 inside the for
loop. So your if
statement only checks the values 1000 to 1999 and the last increment sets it to 2000 (but that value isn't checked because the loop ends.
So no values match and the final value of counter
(2000) is returned.
I would change the for
loop to be clearer. If you want to check the numbers in the range 2000 - 3000, then state that:
for counter in 2000...3000 {
and get rid of the var counter = ...
line.
You might also want to change the returned value to indicate that no match was found. This would be a good use for an optional.
I'd also provide parameters to your function to specify the range.
func divisibleByAllTenNumbers(_ from: Int, to: Int) -> Int? {
for counter in from...to {
if counter % 2 == 0 && counter % 3 == 0 &&
counter % 4 == 0 && counter % 5 == 0 &&
counter % 6 == 0 && counter % 7 == 0 &&
counter % 8 == 0 && counter % 9 == 0 &&
counter % 10 == 0 {
return counter
}
}
return nil
}
if let result = divisibleByAllTenNumbers(2000, to: 3000) {
print("Found result of \(result)")
} else {
print("No match found")
}
Output:
Found result of 2520
Upvotes: 1