Check if an integer is divisible by another integer (Swift)
Solution 1
You can use the modulo operator %
:
numberTwo % numberOne == 0
The modulo finds the remainder of an integer division between 2 numbers, so for example:
20 / 3 = 6
20 % 3 = 20 - 6 * 3 = 2
The result of 20/3 is 6.666667 - the dividend (20) minus the integer part of that division multiplied by the divisor (3 * 6) is the modulo (20 - 6 * 3) , equal to 2 in this case.
If the modulo is zero, then the dividend is a multiple of the divisor
More info about the modulo at this wikipedia page.
Solution 2
1) If you want to check or an integer is divided by another integer:
Swift 5
if numberOne.isMultiple(of: numberTwo) { ... }
Swift 4 or less
if numberOne % numberTwo == 0 { ... }
2) Function to round to the closest multiple value:
func roundToClosestMultipleNumber(_ numberOne: Int, _ numberTwo: Int) -> Int {
var result: Int = numberOne
if numberOne % numberTwo != 0 {
if numberOne < numberTwo {
result = numberTwo
} else {
result = (numberOne / numberTwo + 1) * numberTwo
}
}
return result
}
Solution 3
Swift 5
isMultiple(of:)
Returns true if this value is a multiple of the given value, and false otherwise.
func isMultiple(of other: Int) -> Bool
let rowNumber = 4
if rowNumber.isMultiple(of: 2) {
print("Even")
} else {
print("Odd")
}
Solution 4
You can use truncatingRemainder
. E.g.,
if number.truncatingRemainder(dividingBy: 10) == 0 {
print("number is divisible by 10")
}
Related videos on Youtube
Tom Coomer
Updated on June 09, 2022Comments
-
Tom Coomer almost 2 years
I need to check if an integer is divisible by another integer exactly.
If not I would like to round it up to the closest multiple of the number.
Example:
var numberOne = 3 var numberTwo = 5
numberTwo
is not a multiple ofnumberOne
therefore I would like it to roundnumberTwo
up to 6.How would I do this? Thank you
-
Tom Coomer over 9 yearsThe first part is working for me however I am not sure what the bottom line means. How do I work out what I should add to the 20 to make it divisible by 3? I would like to round it up. Thanks
-
Antonio over 9 yearsUpdated the answer - hope that explains a little bit.