Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created January 11, 2020 00:25
Show Gist options
  • Select an option

  • Save misterpoloy/24e990e9fecadb8310ecacd300e98fbb to your computer and use it in GitHub Desktop.

Select an option

Save misterpoloy/24e990e9fecadb8310ecacd300e98fbb to your computer and use it in GitHub Desktop.
Prime factorization of a number
// https://www.youtube.com/watch?v=6PDtgHhpCHo&list=PL2_aWCzGMAwLL-mEB4ef20f3iqWMGWa25&index=7&t=0s
#include <iostream>
#include <list>
#include <cmath>
std::list<int> getPrimeFactors(int n) {
std::list<int> factors;
int times = n;
// Optimization to BIG O(sqrt(n))
for (int i = 2; i < sqrt(n); i++) {
if (n % i == 0) {
while (times % i == 0) {
factors.push_back(i);
times = times / i;
}
}
}
// part of the optimization
if (times != 1) {
factors.push_back(times);
}
return factors;
}
int main() {
int n = 238;
std::list<int> factors = getPrimeFactors(n);
for (int n : factors) {
std::cout << n << ", " << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment