From 04a1c29a4b63f2aa12e26e629345f268ff1a27cd Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Mon, 28 Jan 2019 13:13:13 -0500 Subject: [PATCH] Added a function to get all the prime factos of a number --- Algorithms.hpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Algorithms.hpp b/Algorithms.hpp index 5b61898..1813290 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 all prime factors of a number +template +std::vector getFactors(T goalNumber); //This is a function that gets all the divisors of num and returns a vector containing the divisors template std::vector getDivisors(T num); @@ -108,6 +111,34 @@ std::vector getPrimes(T goalNumber){ 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) + std::vector primes = getPrimes((T)ceil(sqrt(goalNumber))); //Make sure you are getting a vector of the correct type + std::vector factors; + + //Need to step through each prime and see if it is a factor of the number + for(int cnt = 0;cnt < primes.size():){ + if((goalNumber % primes[cnt]) == 0){ + factors.push_back(primes[cnt]); + goalNumber /= primes[cnt]; + } + else{ + ++cnt; + } + } + + //If it didn't find any factors in the primes the number itself must be prime + if(factors.size() == 0){ + factors.push_back(goalNumber); + goalNumber /= goalNumber; + } + + ///Should add some kind of error throwing inc ase the number != 1 after searching for all prime factors + + return 0; +} + template std::vector getDivisors(T num){ std::vector divisors; //Holds the number of divisors