GCD
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 672 Accepted Submission(s): 295
Problem Description
The greatest common divisor GCD(a,b) of two positive integers a and b,sometimes written (a,b),is the largest divisor common to a and b,For example,(1,2)=1,(12,18)=6.
(a,b) can be easily found by the Euclidean algorithm. Now Carp is considering a little more difficult problem:
Given integers N and M, how many integer X satisfies 1<=X<=N and (X,N)>=M.
(a,b) can be easily found by the Euclidean algorithm. Now Carp is considering a little more difficult problem:
Given integers N and M, how many integer X satisfies 1<=X<=N and (X,N)>=M.
Input
The first line of input is an integer T(T<=100) representing the number of test cases. The following T lines each contains two numbers N and M (2<=N<=1000000000, 1<=M<=N), representing a test case.
Output
For each test case,output the answer on a single line.
Sample Input
3 1 1 10 2 10000 72
Sample Output
1 6 260
解题: eular函数
思路:
/*
/*
把所有的 n 的 约数找出来,然后 n = p * d,那我们现在把每一个最大公约数为 d 的全部找出来,怎样找呢?肯定是 x = q * d,显然 q 得与 p 互质,这样才能保证 n 跟 x 的最大公约数是 d,然后我们就只要把所有的 d 找出来就行了,然后就只要找 p 的质因子就行了,这不就是欧拉吗?
*/
*/
#include<cstdio> #include<cmath> using namespace std; const int MAXN=50000; __int64 pri[MAXN]; bool hash[MAXN]; __int64 N,M,s; void Is_pri() { __int64 i,j; pri[0]=0; for(i=2;i<MAXN;i++) { if(!hash[i]) { pri[++pri[0]]=i; for(j=i*i;j<MAXN;j+=i) hash[j]=true; } } } __int64 eular(__int64 n) { __int64 tmp=n,i; for(i=2;i*i<=n;i++) { if(n%i==0) { tmp-=tmp/i; while(n%i==0) n/=i; } } if(n>1) tmp-=tmp/n; return tmp; } void DFS(__int64 x,int flag) { int i; if(x>=M) { s+=eular(N/x); // printf("%I64d %I64d\n",x,s); } for(i=flag;i<=pri[0]&&pri[i]*x<=N;i++) { if(N%(pri[i]*x)==0) DFS(pri[i]*x,i); } } int main() { int T; int i,j; scanf("%d",&T); Is_pri(); while(T--) { scanf("%d%d",&N,&M); s=0; DFS(1,1); printf("%d\n",s); } return 0; }
网上找到的,思路和我一样,但是代码更犀利,用的时间更短的代码。
#include<iostream> #include<cstdio> using namespace std; const int Max = 1000000005; int num[40000],cnt2; int Eular( int n ) { int ret = 1; for( int i = 2; i * i <= n; ++i ) { int temp = i; if( n % temp == 0 ) { ret *= ( temp - 1 ); n /= temp; while( n % temp == 0 ) ret *= temp,n /= temp; } } if( n > 1 ) ret *= ( n - 1 ); return ret; } int main( ) { int i,Cas; scanf( "%d",&Cas ); while( Cas-- ) { int n,m; scanf( "%d%d",&n,&m ); cnt2 = 0; for(i = 1; i * i <= n; ++i ) if( n % i == 0 ) { num[cnt2++] = i; if( i * i < n ) num[cnt2++] = n / i; } int s = 0; for(i = 0; i < cnt2; ++i ) if( num[i] >= m ) s += Eular( n / num[i] ); printf( "%d\n",s ); } return 0; }