In Lua, how can I tell if a number divides evenly into another number? i.e with no remainder? I'm just looking for a boolean true or false.
12/6 = 2 (true)
18/6 = 3 (true)
20/6 = 3.(3) (false)
1) A number that divides another number evenly is called a factor of that number. For example, 16 can be divided evenly by 1, 2, 4, 8, and 16. So the numbers 1, 2, 4, 8, and 16 are called factors of 16.
All even numbers are divisible by 2. Therefore, a number is divisible by 2 if it has a 0, 2, 4, 6, or 8 in the ones place. For example, 54 and 2,870 are divisible by 2, but 2,221 is not divisible by 2. A number is divisible by 4 if its last two digits are divisible by 4.
Every even number is divisible by 2. That is, any number that ends with 2, 4, 6, 8, or 0 will give 0 as the remainder when divided by 2. For example, 12, 46, and 780 are all divisible by 2. If the sum of the digits of a number is divisible by 3, then the number as a whole would also be divisible by 3.
Compare the remainder of the division to zero, like this:
12 % 6 == 0
18 % 6 == 0
20 % 6 ~= 0
The modulus operator (%
) returns the remainder of division. For 12 and 6 it is 0, but for 20 and 6 it is 2.
The formula it uses is: a % b == a - math.floor(a/b)*b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With