diff --git a/Algorithms.hpp b/Algorithms.hpp new file mode 100644 index 0000000..4a4ab18 --- /dev/null +++ b/Algorithms.hpp @@ -0,0 +1,90 @@ +//myClasses/Algorithms.hpp +//Matthew Ellison +// Created: 11-8-18 +//Modified: 11-8-18 +//This file contains the declarations to several algoritms that I have found useful + +#ifndef MEE_ALGORITHMS_HPP +#define MEE_ALGORITHMS_HPP + +#include +#include + + +template +std::vector getPrimes(T goalNumber){ + std::vector primes; + bool foundFactor = false; + + //If the number is 0 or a negative number return an empty vector + if(goalNumber < 1){ + return primes; + } + + //1 divides everything + primes.push_back(1); + //If the number is even 2 is a factor + if((goalNumber % 2) == 0){ + 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 + 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; + } + } + return primes; +} + +template +std::vector getDivisors(T num){ + std::vector divisors; //Holds the number of divisors + //You only need to go to sqrt(number). cnt * cnt is faster than sqrt() + for(int cnt = 1;cnt * cnt <= num;++cnt){ + //Check if the counter evenly divides the number + //If it does the counter and the other number are both divisors + if((num % cnt) == 0){ + if(!isFound(cnt, divisors)){ + divisors.push_back(cnt); + } + if(!isFound(num/cnt, divisors)){ + divisors.push_back(num / cnt); + } + } + } + return divisors; +} + +template +T getSum(std::vector numbers){ + T sum = 0; + for(unsigned int cnt = 0;cnt < numbers.size();++cnt){ + sum += numbers.at(cnt); + } + return sum; +} + +template +bool isFound(T num, std::vector list){ + for(int cnt = 0;cnt < list.size();++cnt){ + if(list.at(cnt) == num){ + return true; + } + } + return false; +} + + +#endif //MEE_ALGORITHMS_HPP