Last active
November 28, 2017 15:28
-
-
Save ratulSharker/6b27d6d31d254f0a81e0db3c801c0019 to your computer and use it in GitHub Desktop.
Finding the prime factorization of an integer
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
#include <map> | |
// | |
// @param number : Of which you want the prime factorization. | |
// @param freq : Where to store the prime factorization result. | |
// | |
void primeFactorization(unsigned long long number, std::map<int, int> &freq) | |
{ | |
// initially divide via 2 | |
// it has a special thing like | |
// shift one bit to right will | |
// do the job, thats why done | |
// separately, another reason for | |
// this is that, next increment to 3 | |
// after that it will increment by 2 | |
while(number > 0 && number % 2 == 0) | |
{ | |
number = number / 2; | |
freq[2]++; | |
} | |
// now start from the next prime 3 | |
int divider = 3; | |
// when reached 1, nothing remain to break | |
while(number > 1) | |
{ | |
// break until the number is break able | |
// and the number can e divided by the divider. | |
while(number > 1 && (number % divider) == 0) | |
{ | |
// breaking the number | |
number = number / divider; | |
// account the frequency of the numbers | |
freq[divider]++; | |
} | |
// this number is no more break able via this divider | |
// try the next divider. | |
// | |
// an optimization could be like: | |
// without incrementing by 2 every times, bring upon the next | |
// prime number then try with it. | |
divider += 2; | |
} | |
} | |
// | |
// Simple usage | |
// | |
std::map<int, int> freq; // storage where the prime factorization is about to be stored. | |
primeFactorization(100, freq); // we want to find the prime factorization of 100. | |
// | |
// keys of the freq map will be the primes. | |
// value against the keys denote the power of key's. | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment