Horizon
Member in Training
Posts: 32
|
Post by Horizon on Mar 23, 2020 16:31:39 GMT
Hello,
Here is a quick question. Whats the best way to detect an odd number? As i'd like to sort odd numbers from even ones (with a rounding down function).
The process I'm looking to achieve is this: If my number is odd then round down to the next lower even number (-1 easy enough).
For example: input = 9 output = 8 input = 6 output = 6 input = 5 output = 4 input = 79 output = 39 etc. etc.
Would using INT to determine if I divide the input number by two that there is a decimal (3 becomes 1.5), but perhaps this is overkill?
Any pointers would be most welcome.
|
|
|
Post by B+ on Mar 23, 2020 16:38:44 GMT
Hello Horizon, I use MOD 2. If number MOD 2 = 0 then PRINT number;" is even." else PRINT number;" is odd."
n MOD m is like dividing a number by m and only looking at the remainder.
7/2 has remainder = 1
8/2 has remainder = 0 because 2 divides 8 perfectly, no Remainder.
INT(number/2) would drop the stuff after decimal so another way
IF number/2 = INT(number/2) then Print "Number is even.")
|
|
Horizon
Member in Training
Posts: 32
|
Post by Horizon on Mar 23, 2020 16:45:29 GMT
Hello B+
That's perfect, thanks so much for the example.
|
|
|
Post by B+ on Mar 23, 2020 16:46:39 GMT
We cross posted, I added a thing about INT.
|
|
|
Post by tsh73 on Mar 23, 2020 18:45:04 GMT
rounding to even
for i = -5 to 10 print "input", i, "output", int(i/2)*2, i - i mod 2 next
|
|
|
Post by B+ on Mar 24, 2020 3:57:22 GMT
Ha! cool tsh73, I always liked 5's and 13's
for i = -5 to 100 print "input", i, "output", int(i/5)*5, int(i/13)*13 next
|
|
ntech
Junior Member
Posts: 99
|
Post by ntech on Mar 24, 2020 18:33:39 GMT
How about this?
function evenNumber(n)
'' ' evenNumber() accepts a number and returns it if it's even ' or else it returns the even number immediately before it. ''
if n/2=int(n/2) then evenNumber = n else evenNumber = n-1 end if
end function
|
|
|
Post by zzz000abc on Mar 26, 2020 18:09:40 GMT
here is one more
for i=-5 to 10 print "input ";i,"output ";i-(abs(i) mod 2 =1) next
|
|