Here is the function as I would implement it, in a very simple way:davisdude wrote:Also, if you don't mind, how would I decrease the amount of time taken? I didn't look up a formula, I just sort of did what made sense to me.
Code: Select all
function mlib.math.prime( n )
if n < 2 then return end
for i = 2, math.sqrt(n) do
if n % i == 0 then
return false
end
end
return true
end
- I return nil for things that are neither prime nor composite number. Since nil is falsy, this works out just as you would want in an if-statement.
- You only need to check up to sqrt(n), because you already checked the numbers larger than that (for example, we don't need to check if 10 % 5 == 0, because we already know that 10 % 2 == 0).
- if math.floor( math.sqrt( num ) ) ~= math.sqrt( num ) then this just checks if num isn't a square. It already gets checked in the for-loop, so it is unneeded.
- For programs that need to check for primes a lot, you'd probably want another solution.
- You can trivially make it twice as fast:
This makes the code a bit elegant and only speeds it up with a constant factor, so I usually wouldn't do that.
Code: Select all
function mlib.math.prime( n ) if n < 2 then return end if n ~= 2 and n % 2 == 0 then return false end for i = 3, math.sqrt(n), 2 do if n % i == 0 then return false end end return true end
Generally, it's a bad idea to make functions do different things when given different arguments, because it leads to confusion and bugs.davisdude wrote:I don't really know of a case where you would check for multiple numbers, but just thought it would be a nice added functionality.