fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <algorithm>
  5. #include <sstream>
  6. #include <cmath>
  7. using namespace std;
  8. int N=65537;
  9. vector<bool> a(N,false);
  10. vector<int> prime;
  11.  
  12. string getPrint(const map<int,int> &v){
  13. string s;
  14. stringstream ss;
  15. for(auto p: v)
  16. if(p.second==1) ss<<p.first<<'*';
  17. else ss<<'('<<p.first<<'^'<<p.second<<')'<<'*';
  18. ss>>s;
  19. s.pop_back();
  20. return s;
  21. }
  22.  
  23. map<int,int> primeFactorization(unsigned int n){
  24. map<int,int> v;
  25. int i=0;
  26. int c=0;
  27. int l=prime.size();
  28. int p;
  29. int s = sqrt(n);
  30. while(n>1){
  31. while(i<l&&prime[i]<=s&&n%prime[i]) i++;
  32. if(i==l||prime[i]>s) p = n;
  33. else p = prime[i];
  34. c=0;
  35. while(n%p==0){
  36. n /= p;
  37. c++;
  38. }
  39. v[p] = c;
  40. s = sqrt(n);
  41. }
  42. return v;
  43. }
  44.  
  45. void initializePrimes(){
  46. int m, n=N;
  47. a[0]=a[1]=true;
  48. for(int i=0; i<=sqrt(n); i++){
  49. if(a[i]) continue;
  50. prime.push_back(i);
  51. m = i*i;
  52. while(m<n){
  53. a[m]=true;
  54. m += i;
  55. }
  56. }
  57. for(int i=sqrt(n); i<n; i++)
  58. if(!a[i]) prime.push_back(i);
  59.  
  60. cout<<"Prime size is "<<prime.size()<<endl;
  61. }
  62.  
  63. int main() {
  64. initializePrimes();
  65. int t,n;
  66. cin>>t;
  67. while(t--){
  68. cin>>n;
  69. cout<<n<<" = "<<getPrint(primeFactorization(n))<<endl;
  70. }
  71. return 0;
  72. }
Success #stdin #stdout 0s 4396KB
stdin
18
9 10
100 17
220 70
17 19
4 18
32 20
100 32
224 385
300008 300009
stdout
Prime size is 6542
9 = (3^2)
10 = 2*5
100 = (2^2)*(5^2)
17 = 17
220 = (2^2)*5*11
70 = 2*5*7
17 = 17
19 = 19
4 = (2^2)
18 = 2*(3^2)
32 = (2^5)
20 = (2^2)*5
100 = (2^2)*(5^2)
32 = (2^5)
224 = (2^5)*7
385 = 5*7*11
300008 = (2^3)*37501
300009 = 3*100003