Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an integer is divisible by another integer (Swift)

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 of numberOne therefore I would like it to round numberTwo up to 6.

How would I do this? Thank you

like image 740
Tom Coomer Avatar asked Nov 27 '14 17:11

Tom Coomer


People also ask

How do you check if a number divides another number?

A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.

How to tell if a number is divisible by 3?

A number is divisible by 3 if sum of its digits is divisible by 3. Illustration: For example n = 1332 Sum of digits = 1 + 3 + 3 + 2 = 9 Since sum is divisible by 3, answer is Yes.


4 Answers

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.

like image 199
Antonio Avatar answered Oct 13 '22 01:10

Antonio


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
}
like image 28
maxwell Avatar answered Oct 13 '22 01:10

maxwell


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")
}
like image 31
Saranjith Avatar answered Oct 13 '22 01:10

Saranjith


You can use truncatingRemainder. E.g.,

if number.truncatingRemainder(dividingBy: 10) == 0 {                
    print("number is divisible by 10")   
}
like image 37
Lawliet Avatar answered Oct 13 '22 00:10

Lawliet