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

if statement for remainder?

Started by Avous, 11 December 2013 - 11:47 PM
Avous #1
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
theoriginalbit #2
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
Avous #3
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
Alice #4
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.
theoriginalbit #5
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