This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
pinksheep00's profile picture

quick question about multiples

Started by pinksheep00, 18 March 2013 - 10:50 PM
pinksheep00 #1
Posted 18 March 2013 - 11:50 PM
is there math or any api that let me compare a variable if its equal to a multiples of number?(e.g. multiples of 5 [5, 10, 15, 20])

e.g. code:

y = 10
x = 0
if x == "multiples of y" then
    return true
end
theoriginalbit #2
Posted 19 March 2013 - 12:14 AM
you can do it with modulo / modulus

y = 10
if y % 5 == 0 then
  print( y.." is a multiple of 5")
else
  print( y.." is not a multiple of 5")
end

alternatively you can use math.fmod to do the same thing. but % is much nicer :P/>
if you use math.fmod do not confuse it with math.modf … modf is designed to return the fraction part, so math.modf(5.3) would return 0.3
pinksheep00 #3
Posted 19 March 2013 - 12:49 AM
you can do it with modulo / modulus

y = 10
if y % 5 == 0 then
  print( y.." is a multiple of 5")
else
  print( y.." is not a multiple of 5")
end

alternatively you can use math.fmod to do the same thing. but % is much nicer :P/>
if you use math.fmod do not confuse it with math.modf … modf is designed to return the fraction part, so math.modf(5.3) would return 0.3

it works :D/>, thank you good sir
btw what does the % exactly do and what the purpose of " == 0 "? can you please explain it clearly? :)/>
theoriginalbit #4
Posted 19 March 2013 - 12:56 AM
btw what does the % exactly do and what the purpose of " == 0 "? can you please explain it clearly? :)/>
% is modulo … modulo is the process of getting the remainder from a divide.
so if we say give it 5 % 6
6 goes into 5, 0 times with a remainder of 5 … so 6 % 5 would equal 5

but if we give it 13 % 6
6 goes into 13, 2 times with a remainder of 1 … so 13 % 6 would equal 1 (remember its remainder)

now if we give it something that goes perfectly, lets say 24
6 goes into 24, 4 times with a remainder of 0 … so 24 % 6 would equal 0

and that is why we have '== 0' … we want to make sure that the return from the % operation is 0, as that means it was a multiple

its really just some simple maths :)/>
remiX #5
Posted 19 March 2013 - 02:57 AM
but if we give it 13 % 6
6 goes into 7, 2 times with a remainder of 1 … so 13 % 6 would equal 1 (remember its remainder)

6 goes into 7 twice? Since when? :P/>
theoriginalbit #6
Posted 19 March 2013 - 02:59 AM
6 goes into 7 twice? Since when? :P/>
Its clearly a typo since i say 13 twice around it!
I changed it from 7 coz then it would have been going into it 1 time with a remainder of 1 … so to avoid confusion in explaining I changed it from 7 to 13.