From 7bec0bd1c7bdfc7c3faf2755bb4684e3ddef8d92 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Wed, 6 Feb 2019 02:00:52 -0500 Subject: [PATCH] Added a function to get a precise number of prime numbers --- Algorithms.lua | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Algorithms.lua b/Algorithms.lua index 9828747..b93c27f 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -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