Imran_Mohammed

Prime Factorization

Feb 9th, 2021 (edited)
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. //In the name of ALLAH
  2. //prime factorization :complexity (sqrt(n)/ln( sqrt(n) ) ) + log2(n)
  3. //Means : Multiple of prime number
  4.  
  5. #include<bits/stdc++.h>
  6. using namespace std;
  7.  
  8. #define optimize() ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  9. #define endl '\n'
  10.  
  11. //Prime Generation
  12. const long long mx = 1e6+123;
  13. bool is_prime[mx];
  14. vector<long long> prime;
  15.  
  16. void primegen ( long long n )
  17. {
  18.     for ( int i = 3; i <= n; i += 2 ) is_prime[i] = 1;
  19.  
  20.     int sq = sqrt ( n );
  21.     for ( int i = 3; i <= sq; i += 2 ) {
  22.         if ( is_prime[i] == 1 ) {
  23.             for ( int j = i*i; j <= n; j += ( i + i ) ) {
  24.                 is_prime[j] = 0;
  25.             }
  26.         }
  27.     }
  28.  
  29. is_prime[2]=1;
  30. prime.push_back(2);
  31.     for ( int i = 3; i <= n; i += 2 ) {
  32.         if ( is_prime[i] == 1 ) prime.push_back ( i );
  33.     }
  34. }
  35.  
  36. //prime Factorization
  37.  
  38. vector <long long> factorization (long long n){
  39.     vector <long long > ret;
  40.     for( auto p:prime){
  41.         if( p*p > n)break;
  42.         if(n%p == 0){
  43.             while(n%p == 0){
  44.                 ret.push_back(p);
  45.                 n = n/p;
  46.             }
  47.         }
  48.     }
  49.  
  50.     if(n > 1)ret.push_back(n);
  51.     return ret;
  52. }
  53.  
  54. //main function
  55. int main()
  56. {
  57.     optimize()
  58.  
  59.     primegen(1e6);
  60.  
  61.     int n;
  62.     cin >> n;
  63.  
  64.     vector<long long> ans = factorization(n);
  65.  
  66.     for(auto u : ans )cout << u << " ";100 = 5 5 4
  67.     cout << endl;
  68.  
  69.  
  70.     return 0;
  71. }
  72.  
Add Comment
Please, Sign In to add comment