Last active
December 14, 2016 13:52
-
-
Save Gaurav-Singh-97/9b8e229bf93ef2d07d44caf69cde20f8 to your computer and use it in GitHub Desktop.
Function for prime factorisation of a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Header containing function primeFactorisation which returns std::map of prime factorisation of number | |
* PROTOTYPE: | |
* std::map<int, int> GS::primeFactorisation(int num); | |
* 'num' is the number for which prime factorisation is required | |
* In the map returned, for each element (i.e. pair), first element is factor and second is its power | |
* E.g. | |
* Prime factorisation of 49 = 2 * 7 * 7 = (2^1) * (7^2) | |
* So, the map would contain pairs (2, 1) and (7, 2), | |
*/ | |
#include <utility> | |
#include <map> | |
namespace GS | |
{ | |
using std::map; | |
using std::make_pair; | |
map<int, int> primeFactorisation(int num) | |
{ | |
map<int, int>pf{}; | |
int fac, origNum = num; | |
for (fac = 2; fac <= origNum/2 && num > 1; ++fac) | |
{ | |
while (num % fac == 0) | |
{ | |
num /= fac; | |
auto ins = pf.insert(make_pair(fac, 1)); | |
if (!ins.second) | |
++ins.first->second; | |
} | |
} | |
return pf; | |
} | |
//namespace GS | |
} | |
/* | |
* TEST CODE : | |
int main() | |
{ | |
int num; | |
cin >> num; | |
auto mp = GS::primeFactorisation(num); | |
for (auto itr : mp) | |
{ | |
if (itr != *mp.begin()) | |
cout << "* "; | |
cout << "( " << itr.first << " ^ " << itr.second << " ) "; | |
} | |
return 0; | |
} | |
* | |
* */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment