From b54a22393412f865f95e4eea6bb237b38e178f30 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Fri, 30 Oct 2020 15:21:23 -0400 Subject: [PATCH] Added isPrime --- Algorithms.hpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Algorithms.hpp b/Algorithms.hpp index 351192c..a62163c 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -34,6 +34,9 @@ namespace mee{ //A list of functions in the file //Also works as prototypes with general information +//This function determines whether the number passed into it is a prime +template +bool isPrime(T num); //This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers template std::vector getPrimes(T goalNumber); @@ -103,6 +106,7 @@ std::vector getPrimes(T goalNumber){ else{ primes.push_back(2); } + //We can now start at 3 and skip all of the even numbers for(T possiblePrime = 3;possiblePrime <= goalNumber;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 @@ -122,6 +126,7 @@ std::vector getPrimes(T goalNumber){ foundFactor = false; } } + std::sort(primes.begin(), primes.end()); return primes; } @@ -168,6 +173,23 @@ std::vector getNumPrimes(T numberOfPrimes){ return primes; } +//This function determines whether the number passed into it is a prime +template +bool isPrime(T num){ + if(num <= 3){ + return num > 1; + } + else if(((num % 2) == 0) || ((num % 3) == 0)){ + return false; + } + for(T cnt = 5;(cnt * cnt) <= num;cnt += 6){ + if(((num % cnt) == 0) || ((num % (cnt + 2)) == 0)){ + return false; + } + } + return true; +} + //This function returns all prime factors of a number template std::vector getFactors(T goalNumber){