Reputation: 123
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)
Upvotes: 10
Views: 17817
Reputation: 1917
The problem with using the modulus operator is, it doesn't work correctly on negative numbers. If you're going to be using negative numbers, use math.fmod
instead:
maxtothemax@maxtothemax-mint ~ $ lua
> return -13%6
5
> return 13%6
1
> return math.fmod (-13, 6)
-1
> return math.fmod (13, 6)
1
>
Upvotes: 1
Reputation: 726809
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
Upvotes: 21