mirror of
https://bitbucket.org/Mattrixwv/luaclasses.git
synced 2025-12-06 18:33:59 -05:00
Added a function to get a precise number of prime numbers
This commit is contained in:
@@ -54,7 +54,53 @@ end
|
||||
|
||||
--This function gets a specific number of primes
|
||||
function getNumPrimes(numberOfPrimes)
|
||||
local primes = {}; --Holds the prime numbers
|
||||
local foundFactor = false;
|
||||
|
||||
--If the number is 0 or negative return an empty table
|
||||
if(numberOfPrimes <= 1) then
|
||||
return primes;
|
||||
--Otherwise the number is at lease 2, therefore 2 should be added to the list
|
||||
else
|
||||
primes[#primes + 1] = 2;
|
||||
end
|
||||
|
||||
--We can now start at 3 and skip all even numbers, because they cannot be prime
|
||||
possiblePrime = 3;
|
||||
while((#primes < numberOfPrimes) and (possiblePrime >= 0)) do
|
||||
--Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
|
||||
primesCnt = 1;
|
||||
--We can safely assume that there will be at least 1 element in the primes list because of 2 being added before the loop
|
||||
topPossibleFactor = math.ceil(math.sqrt(possiblePrime))
|
||||
while(primes[primesCnt] <= topPossibleFactor) do
|
||||
if((possiblePrime % primes[primesCnt]) == 0) then
|
||||
foundFactor = true;
|
||||
break;
|
||||
else
|
||||
primesCnt = primesCnt + 1;
|
||||
end
|
||||
--Check if the index has gone out of range
|
||||
if(primesCnt >= #primes) then
|
||||
break;
|
||||
end
|
||||
end
|
||||
|
||||
--If you didn't find a factor then the current number must be prime
|
||||
if(not foundFactor) then
|
||||
primes[#primes + 1] = possiblePrime;
|
||||
else
|
||||
foundFactor = false;
|
||||
end
|
||||
|
||||
--Advance to the next possible prime number
|
||||
possiblePrime = possiblePrime + 2;
|
||||
end
|
||||
|
||||
--Sort the array just to be neat and safe
|
||||
table.sort(primes);
|
||||
|
||||
--Return the array
|
||||
return primes;
|
||||
end
|
||||
|
||||
--This is a function that returns all the factors of goalNumber
|
||||
|
||||
Reference in New Issue
Block a user