Advertisement
jasonpogi1669

Get the Prime Factors of a number using C++

Dec 22nd, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. vector<int> GetPrimeFactors(int n) {
  6.     vector<int> prime;
  7.     // get the 2 prime factors
  8.     while (n % 2 == 0) {
  9.         prime.push_back(2);
  10.         n /= 2;
  11.     }
  12.     // get the other prime factors (starting from 3 and
  13.     // skipping every even number because we already did it above)
  14.     for (int i = 3; i * i <= n; i += 2) {
  15.         while (n % i == 0) {
  16.             prime.push_back(i);
  17.             n /= i;
  18.         }
  19.     }
  20.     // if n is still greater than 2, then store n itself (it means n is a prime number)
  21.     if (n > 2) {
  22.         prime.push_back(n);
  23.     }
  24.     return prime;
  25. }
  26.  
  27. int main() {
  28.     int n;
  29.     cin >> n;
  30.     vector<int> factors = GetPrimeFactors(n);
  31.     for (auto& e : factors) {
  32.         cout << e << " ";
  33.     }
  34.     cout << '\n';
  35.     return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement