Advertisement

LightOJ1236 Pairs Forming LCM 素数筛法+分解质因数

阅读量:

Description

Find the result of the following code:

long long pairsFormLCM( int n ) {
long long res = 0;
for( int i = 1; i <= n; i++ )
for( int j = i; j <= n; j++ )
if( lcm(i, j) == n ) res++; // lcm means least common multiple
return res;
}

A straight forward implementation of the code may time out. If you analyze the code, you will find that the code actually counts the number of pairs(i, j) for which lcm(i, j) = n and (i ≤ j).

Input

Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1014).

Output

For each case, print the case number and the value returned by the function 'pairsFormLCM(n)'.

Sample Input

15

2

3

4

6

8

10

12

15

18

20

21

24

25

27

29

Sample Output

Case 1: 2

Case 2: 2

Case 3: 3

Case 4: 5

Case 5: 4

Case 6: 5

Case 7: 8

Case 8: 5

Case 9: 8

Case 10: 8

Case 11: 5

Case 12: 11

Case 13: 3

Case 14: 4

Case 15: 2

这道题就是求最小公倍数为n的数对对数,按题中所给程序枚举必定超时,因为n可取到10的14次;

而两个数的最小公倍数有这样一个性质,即他们的最小公倍数中,任意一个素因子的次数均是这两个数中所含该素因子次数的最大值,因此,先将n素因子分解,用下素数筛法即可;

然后,不妨假设n=p1x1*p2x2p3x3*---*pkxk, 则对于任意素因子ps, i 和 j 必有一个等于xs,而另一个可以为小于等于xs的任意值,那么,对于ps ,可供选择的的组合方式有2xs+1 种,(注意两者均可等于xs),(此时先不考虑两个数大小问题);

这样可得的结果为(2x1+1)(2x2+1)---(2xk+1),但此处有个细节,因为 n可取到10的14次,对于素数筛法而言,n确实还是太大了,因此只需对10的7次范围内进行素数筛法即可,因为大于10的7次,小于10的14次的数如果不是素数,那就一定含有小于10的7次的素因子,这样处理的话,遇到比10的7次大的素数,只需最后再加一句判断即可;

当然,这样还没有得到最后答案,因为题中规定的两个数的大小,不过不用担心,上面的过程已经得到了所有的情况的种数,很容易知道除二可以得到最后答案,但是应先加个1(可以自己想想为什么,试几组数据也可以得到)。

复制代码
 #include <iostream>

    
 #include <cstdio>
    
 #include <map>
    
 #include <cmath>
    
 #include <map>
    
 #include <vector>
    
 #include <algorithm>
    
 #include <cstring>
    
 #include <string>
    
 using namespace std;
    
 #define LL long long
    
 #define maxn 10000001
    
 bool v[maxn];
    
 vector<int>prime;
    
 void p(){
    
     memset(v,false,sizeof(v));
    
     for(int i=2;i<=maxn;i++){
    
     if(v[i])continue;
    
     for(int j=i+i;j<=maxn;j+=i){
    
         v[j]=true;
    
     }
    
     if(!v[i]) prime.push_back(i);
    
     }
    
 }
    
 int main()
    
 {
    
     int t,ca=1;
    
     LL n,ans;
    
     p();
    
     scanf("%d",&t);
    
     while(t--){
    
     ans=1;
    
     scanf("%lld",&n);
    
     for(int i=0;i<prime.size()&&n>1;i++){
    
         if(n%prime[i]==0){
    
             LL s=0;
    
             while(n%prime[i]==0){
    
                 s++;
    
                 n/=prime[i];
    
             }
    
             ans*=(s*2+1);
    
         }
    
     }
    
     if(n>1){
    
         ans*=3;
    
     }
    
     printf("Case %d: %lld\n",ca++,(ans+1)/2);
    
     }
    
     return 0;
    
 }

全部评论 (0)

还没有任何评论哟~