bhupixb

Generating divisors recursively using prime factorization

Oct 26th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5.  
  6. #define int long long
  7. #define F first
  8. #define S second
  9. #define sz(x) ((int)x.size())
  10. #define rep(i,a,n) for (int i = a; i <= n; ++i)
  11. #define all(v) v.begin(), v.end()
  12. #define pb push_back
  13. #define P pair < int, long long >
  14. #define E cout << '\n'
  15.  
  16. const int mod = 1e9 + 7;
  17. const int N = 1e5 + 5;
  18.  
  19. int a[N], k, currElement, ans = 0;
  20. vector < P > v;
  21. int h[N];
  22.  
  23. void generateDivisors(int idx, long long cur) {
  24. if (idx >= sz(v))return;
  25. for (int i = 0; i <= v[idx].first; ++i) {
  26. // To prevent it from number of divisors extra calls
  27. if (idx + 1 < sz(v)) {
  28. generateDivisors(idx+1, cur);
  29. cur *= v[idx].S;
  30. }
  31. else {
  32. // let's consider this prime factorization
  33. // {{1,2}, {2,3}, {2,5}, {1,7}} in this example 7 will never be multiplied
  34. // in if condition as idx + 1 == sz(v) so we multiply it in else condition if i > 0
  35. if (i) {
  36. cur *= v[idx].S;
  37. }
  38. // Here cur is the divisors formed
  39. cout << cur << ' ';
  40. }
  41. }
  42. }
  43.  
  44. vector < int > primes;
  45. vector < int > spf;
  46.  
  47. void RunLinearSieve() {
  48. int n = N;
  49. spf.assign(n + 1, 0);
  50. spf[1] = 1;
  51. for(int i = 2; i < n; ++i) {
  52. if(!spf[i]) {
  53. spf[i] = i;
  54. primes.push_back(i);
  55. }
  56. for(int x : primes) {
  57. int calc = i * x;
  58. if(x > spf[i] || calc > n) {
  59. break;
  60. }
  61. spf[calc] = x;
  62. }
  63. }
  64. }
  65.  
  66. void findPrimefactors(int n) {
  67. while (n != 1) {
  68. int ok = 1, pf = spf[n], cnt = 0;
  69. while (n > 1 && n % pf == 0) {
  70. ok *= pf;
  71. n /= pf;
  72. ++cnt;
  73. }
  74. v.push_back({cnt, pf});
  75. }
  76. }
  77.  
  78. inline void solve() {
  79. int n;
  80. cin >> n;
  81. v.clear();
  82. findPrimefactors(n);
  83. generateDivisors(0, 1);
  84. }
  85. signed main() {
  86. ios_base::sync_with_stdio(0);
  87. cin.tie(NULL);
  88. cout.tie(NULL);
  89. RunLinearSieve();
  90. solve();
  91. return 0;
  92. }
Add Comment
Please, Sign In to add comment