Added a file that contains some useful algorithms

This commit is contained in:
2018-11-08 18:00:06 -05:00
parent 00759b82d1
commit 72153267df

90
Algorithms.hpp Normal file
View File

@@ -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 <vector>
#include <cinttypes>
template<class T>
std::vector<T> getPrimes(T goalNumber){
std::vector<T> 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<class T>
std::vector<T> getDivisors(T num){
std::vector<T> 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 <class T>
T getSum(std::vector<T> numbers){
T sum = 0;
for(unsigned int cnt = 0;cnt < numbers.size();++cnt){
sum += numbers.at(cnt);
}
return sum;
}
template<class T>
bool isFound(T num, std::vector<T> list){
for(int cnt = 0;cnt < list.size();++cnt){
if(list.at(cnt) == num){
return true;
}
}
return false;
}
#endif //MEE_ALGORITHMS_HPP