diff --git a/Algorithms.hpp b/Algorithms.hpp index 1813290..fbd2233 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -39,6 +39,9 @@ namespace mee{ //This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers template std::vector getPrimes(T goalNumber); +//This function returns a vector with a specific number of primes +template +std::vector getNumPrimes(T numberOfPrimes); //This function returns all prime factors of a number template std::vector getFactors(T goalNumber); @@ -111,6 +114,45 @@ std::vector getPrimes(T goalNumber){ return primes; } +template +std::vector getNumPrimes(T numberOfPrimes){ + std::vector primes; + bool foundFactor = false; + + //If the number is 0 or a negative number return an empty vector + if(goalNumber < 1){ + return primes; + } + //Otherwise 2 is the first prime number + else{ + primes.push_back(2); + } + + //Loop through every odd number starting at 3 until we find the requisite number of primes + //Using possiblePrime >= 3 to make sure it doesn't loop back around in an overflow error and create an infinite loop + for(T possiblePrime = 3;(primes.size() < numberOfPrimes) && (possiblePrime >= 3);possiblePrime += 2){ + //Step through every element in the current primes. If you don't find anything that divides it, it must be a prime itself + for(uint64_t cnt = 0;(cnt < primes.size()) && ((primes.at(cnt) * primes.at(cnt)) < goalNumber);++cnt){ + if((possiblePrime % primes.at(cnt)) == 0){ + foundFactor = true; + break; + } + } + //If you didn't find a factor then it must be prime + if(!foundFactor){ + primes.push_back(possiblePrime); + } + //If you did find a factor you need to reset the flag + else{ + foundFactor = false; + } + } + + //The numbers should be in order, but sort them anyway just in case + std::sort(primes.begin(), primes.end()); + return primes; +} + template std::vector getFactors(T goalNumber){ //Get all the prime numbers up to sqrt(number). If there is a prime < goalNumber it will have to be <= sqrt(goalNumber)