1
how do you tell if a number is even or odd
Started by ETHANATOR360, Mar 25 2013 12:35 PM
28 replies to this topic
#1
Posted 25 March 2013 - 12:35 PM
title says it all
#2
Posted 25 March 2013 - 12:41 PM
you can use division.......
#3
Posted 25 March 2013 - 12:44 PM
in java, i know you can do this
var Num = 4 if (Num % 2 === Num/2) { Number is even } else { Number is odd }its java though (tinn57, syntax?)
#4
Posted 25 March 2013 - 12:55 PM
i know java im asuming mod symbol works in lua
#6
Posted 25 March 2013 - 01:07 PM
Here's a simple function for you:
function GetType(Number)
local Derp = Number % 2
if Derp == 0 then
return "Even"
else
return "Odd"
end
end
function GetType(Number)
local Derp = Number % 2
if Derp == 0 then
return "Even"
else
return "Odd"
end
end
#7
Posted 25 March 2013 - 01:41 PM
Another nice way is to use bitwise operators, every even number has a zero last bit. To check this:
Although im not sure how much of a difference this makes in lua.
function getType(number) if bit.band(number,1) == 0 then return "Even" end return "Odd" end
Although im not sure how much of a difference this makes in lua.
#8
Posted 25 March 2013 - 01:46 PM
Either way works. It is up to him what he wants to use. I would rather use the bitwise operator.
#9
Posted 25 March 2013 - 01:58 PM
It's much easier, way faster, and native to lua to use the modulo operator.
function isEven(num) return num % 2 == 0 end
#10
Posted 25 March 2013 - 01:59 PM
I guess that works as well Still a fan of the bitwise operator
#11
Posted 25 March 2013 - 02:07 PM
Im still new to lua, so as i said i wasn't sure if the bitwise operator had an advantage over the modulo operator. I know that in some languages it definitely does.
#12
Posted 25 March 2013 - 02:11 PM
In this case, the modulo operator has the bitwise operator beaten. I still like it though
#13
Posted 25 March 2013 - 02:26 PM
modulo = java
#14
Posted 25 March 2013 - 02:29 PM
Java = nil
#17
#20
Posted 25 March 2013 - 03:21 PM
Kingdaro, on 25 March 2013 - 03:15 PM, said:
Wait. Why does modf even exist? It's ridiculously easy to make modf yourself.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users