Advertisement
Alhiris

Untitled

Feb 8th, 2019
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1.    
  2. #include <fstream>
  3. std::ifstream cin("pinex.in");
  4. std::ofstream cout("pinex.out");
  5. #define ll long long
  6. #define maxn 1000005
  7. ll m,a,b,facts[80000];
  8. bool ciur[maxn];
  9.  
  10. void preCalcPrimes(){
  11.     for(int i=4;i<maxn;i+=2)
  12.         ciur[i]=1;
  13.     facts[++facts[0]]=2;
  14.     for(int i=3;i<maxn;i+=2){
  15.         if(!ciur[i]){
  16.             facts[++facts[0]]=i;
  17.             for(int j=i+i+i;j<maxn;j+=(i<<1))
  18.                 ciur[j]=1;
  19.         }
  20.     }
  21. }
  22.  
  23.  
  24. ll solve(ll a,ll b){
  25.     ll prod=1,sol=a;
  26.     int t=0,nr,nrprim[50],cnt=0;
  27.     while(b>1){
  28.         ++cnt;
  29.         if(b%facts[cnt]==0){
  30.             nrprim[++t]=facts[cnt];
  31.             while(b%facts[cnt]==0)
  32.                 b/=facts[cnt];
  33.         }
  34.         if(facts[cnt]*facts[cnt]>b&&b>1){
  35.             nrprim[++t]=b;
  36.             b=1; break;
  37.         }
  38.     }
  39.     for(int i=1;i<(1<<t);i++){
  40.         nr=0,prod=1;
  41.         for(int j=0;j<t;j++)
  42.             if((1<<j)&i){
  43.                 prod=1LL*prod*nrprim[j+1];
  44.                 nr++;
  45.             }
  46.         if(nr%2)nr=-1;
  47.         else nr=1;
  48.         sol+=(a/prod*nr);
  49.     }
  50.     return sol;
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56.     cin>>m;
  57.     preCalcPrimes();
  58.     for(;m--;){
  59.         cin>>a>>b;
  60.         cout<<solve(a,b)<<'\n';
  61.     }
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement