Created
January 11, 2020 00:25
-
-
Save misterpoloy/24e990e9fecadb8310ecacd300e98fbb to your computer and use it in GitHub Desktop.
Prime factorization of a number
This file contains hidden or 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
| // 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