jasonpogi1669

Find the Number of Prime Factors of a number using C++

Oct 6th, 2021
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int GetFactorization(int n) {
  6.     int cnt = 0;
  7.     // find the number of 2s that will divide 'n'
  8.     while (n % 2 == 0) {
  9.         cnt++;
  10.         n /= 2;
  11.     }
  12.     // find the other factors of 'n' (skip the even numbers since we already divided it by 2 previously)
  13.     for (int i = 3; i <= (int) sqrt(n); i += 2) {
  14.         while (n % i == 0) {
  15.             cnt++;
  16.             n /= i;
  17.         }
  18.     }
  19.     // if 'n' is still greater than 1, then increment 'cnt' (it means 'n' is a prime number)
  20.     if (n > 1) {
  21.         cnt++;
  22.     }
  23.     return cnt;
  24. }
  25.  
  26. int main() {
  27.     int n;
  28.     cin >> n;
  29.     int cnt = GetFactorization(n);
  30.     cout << cnt << '\n';
  31.     return 0;
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment