Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua, how can I tell if a number divides evenly into another number?

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)
like image 652
Scott Phillips Avatar asked Jan 21 '12 01:01

Scott Phillips


People also ask

What does it mean if a number divides another number evenly?

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.

How do you know if a number is divisible by 2?

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.

How do you figure out how many times a number is divisible by 2?

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.


1 Answers

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

like image 168
Sergey Kalinichenko Avatar answered Oct 06 '22 13:10

Sergey Kalinichenko