31 posts
Posted 12 December 2013 - 12:47 AM
I need to have two scenarios laid out if there is a remainder after dividing how can I check for this and add an if statement to it for both scenarios.
So, simply put. I need to add an if statement run if a number has a remainder and have another if statement run if it is a whole number.
Edited on 11 December 2013 - 11:53 PM
7508 posts
Location
Australia
Posted 12 December 2013 - 12:52 AM
you can do this by using the modulo/modulus operator.
if num % 5 == 0 then
print("yep")
else
print("nope")
end
So if the above code is run with num as 35 it would print "yep" because 35 divides into 5, 7 times with a remainder of 0. if it was run with 36 it would print "nope" because 36 divides into 5, 7 times with a remainder of 1.
Edited on 11 December 2013 - 11:52 PM
31 posts
Posted 12 December 2013 - 12:54 AM
you can do this by using the modulo/modulus operator.
if num % 5 == 0 then
print("yep")
else
print("nope")
end
So if the above code is run with num as 35 it would print "yep" because 35 divides into 5, 7 times with a remainder of 0. if it was run with 36 it would print "nope" because 36 divides into 5, 7 times with a remainder of 1.
thank you
882 posts
Location
Behind you.
Posted 12 December 2013 - 08:41 PM
To check if a number is prime using this method, now that I think of it.
local isPrime = true
local num = 35
for i=1, num do
if num % i == 0 then
isPrime = false
end
term.write("Number " .. tostring(num) .. " is prime: ")
if isPrime == true then
print("true.")
else
print("false.")
end
This code should work, but I can't test it right now.
7508 posts
Location
Australia
Posted 12 December 2013 - 09:13 PM
To check if a number is prime using this method, now that I think of it.
Uhhh what. This is not what the OP asked for, they were wanting to check for whole numbers, not prime numbers.
Even so there are ways to make your solution better! Also, use a function!
Code Improved
function isPrime(n)
local n = tonumber(n)
--# check that it is a number
--# make sure that it is not 0 or 1 (which aren't primes)
--# make sure that it is a whole number
--# make sure that it is not a multiple of 2
--# make sure that it is not a multiple of 5
if not n or (n < 2 or (n % 1 ~= 0)) or (n > 2 and (n % 2 == 0)) or (n > 5 and (n % 5 == 0)) then
return false
end
--# since we know its not a multiple of 2, only perform the check on the odd numbers
local limit = math.sqrt(n)
for i = 3, limit, 2 do
if n % i == 0 then
--# it is not a prime
return false
end
end
--# it is a prime
return true
end