Here is my Lua code for taking user input, and checking if the number entered is prime. My issue is that the program thinks that any even number is not prime, and any odd number is.
print("Enter a number.")
local number = io.read("*n")
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
return true
end
end
if prime(number) == true then
print("Your number is prime!")
end
if prime(number) == false then
print("Your number is not prime!")
end
Move return true
out of the loop.
Hence:
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
end
return true
end
You return true too soon. You return true as soon as any i
meets the condition. You must place the return after the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With