Created
January 10, 2020 23:39
-
-
Save misterpoloy/0199061f88a5715dc8bedac5fffd8745 to your computer and use it in GitHub Desktop.
Find all factors of a number using c++
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=dolcMgiJ7I0&list=PL2_aWCzGMAwLL-mEB4ef20f3iqWMGWa25&index=6&t=0s | |
#include <iostream> | |
#include <list> | |
#include <cmath> | |
// Big O(sqrt(n)) | |
std::list<int> getFactors(int n) { | |
std::list<int> factors; | |
for (int i = 1; i <= sqrt(n); i++) { | |
int residuo = n % i; | |
if (residuo == 0) { | |
int b = n / i; | |
factors.push_back(i); | |
// Add only once if b is sqrt of n, eg 36, 6x6 | |
if (b != sqrt(n)) | |
factors.push_back(b); | |
} | |
} | |
return factors; | |
} | |
int main() { | |
int number; | |
std::cout << "Ingresa el número" << std::endl; | |
std::cin >> number; | |
std::cout << "factores:" << std::endl; | |
std::list<int> factors = getFactors(number); | |
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