Added isPrime

This commit is contained in:
2020-10-30 15:21:23 -04:00
parent 1ee5d04871
commit b54a223934

View File

@@ -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 <class T>
bool isPrime(T num);
//This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers
template <class T>
std::vector<T> getPrimes(T goalNumber);
@@ -103,6 +106,7 @@ std::vector<T> 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<T> getPrimes(T goalNumber){
foundFactor = false;
}
}
std::sort(primes.begin(), primes.end());
return primes;
}
@@ -168,6 +173,23 @@ std::vector<T> getNumPrimes(T numberOfPrimes){
return primes;
}
//This function determines whether the number passed into it is a prime
template <class T>
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 <class T>
std::vector<T> getFactors(T goalNumber){