Page 5 of 5

Re: mlib: Math Library

Posted: Sun Dec 29, 2013 6:18 pm
by Robin
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.
Here is the function as I would implement it, in a very simple way:

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
Things of note:
  • 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:

    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
    This makes the code a bit elegant and only speeds it up with a constant factor, so I usually wouldn't do that.
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. :D
Generally, it's a bad idea to make functions do different things when given different arguments, because it leads to confusion and bugs.

Re: mlib: Math Library

Posted: Sun Dec 29, 2013 6:48 pm
by davisdude
Your code is certainly a lot better looking than mine. :)
Thanks for that!
Robin wrote:Generally, it's a bad idea to make functions do different things when given different arguments, because it leads to confusion and bugs.
Okay, I understand now. Thanks!

Re: Math & Collisoins library

Posted: Sun Jan 26, 2014 9:45 pm
by davisdude
2.0.0 is out now! MLib now handles collisions and math! Fun fun fun!
Also did various bug fixes and other stuff. Check out the GitHub!