Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Prime Number Checker

Tags:

numbers

lua

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
like image 799
Nicholas Rubin Avatar asked Dec 01 '22 23:12

Nicholas Rubin


2 Answers

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
like image 176
lhf Avatar answered Dec 05 '22 13:12

lhf


You return true too soon. You return true as soon as any i meets the condition. You must place the return after the loop.

like image 25
Puppy Avatar answered Dec 05 '22 12:12

Puppy