Skip to content

Instantly share code, notes, and snippets.

@obikag
Created September 19, 2013 00:03
Show Gist options
  • Save obikag/6617474 to your computer and use it in GitHub Desktop.
Save obikag/6617474 to your computer and use it in GitHub Desktop.
Prime number functions done in Lua. First function determines if a number is prime, while the second function print to screen the first 'n' prime numbers. View comments for more information.
---Function to determine if a number is a prime number
function isPrime(num)
if num <= 0 then
print("Number must be a positive integer greater than zero")
return false
elseif num == 1 then return true end
--[[Prime number is divisable by itself and one,
so we check for other factors between the prime number and one. (1 < x < num)
]]
for x = num-1,2,-1 do
if (((num % x) == 0) and x > 1) then
return false
end
end
return true
end
--Funtion to print the first 'n' prime numbers
function printPrime(n)
local count = 1
local pnum = 1
repeat
if isPrime(pnum) then
print(pnum)
pnum = pnum + 1
count = count + 1 -- count only incremented when a prime number is found
else
pnum = pnum + 1
end
until(count > n)
end
--***Test Section***
print(isPrime(1)) --True
print(isPrime(-2)) --Number must be a positive integer greater than zero; False
print(isPrime(51)) --False
print(isPrime(3037)) --True
printPrime(10)
--[[
Output:
1
2
3
5
7
11
13
17
19
23
]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment