Pairs Forming LCM (数论)质因数分解+素数筛。

题目:https://vjudge.net/contest/242286#problem/D

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=p1^x1*p2^x2**************pn^xn;

a=p1^y1*p2^y2*p3^y3*****************pn^yn;

b=p1^c1*p2^c2*p3^c3*****************pn^cn;

gcd(a,b)=p1 ^ min(a1,b1) * p2 ^ min(a2,b2) *..........*pn ^ min(an,bn)

lcm(a,b)=p1 ^ max(a1,b1) * p2 ^ max(a2,b2) *..........*pn ^ max(an,bn)

所以,当lcm(a,b)==n时,max(a1,b1)==e1,max(a2,b2)==e2,…max(ak,bk)==ek

当ai == ei时,bi可取 [0, ei] 中的所有数  有 ei+1 种情况,bi==ei时同理。

那么就有2(ei+1)种取法,但是当ai = bi = ei 时有重复,所以取法数为2(ei+1)-1=2*ei+1。
除了 (n, n) 所有的情况都出现了两次  那么满足a<=b的有 (2*ei + 1)) / 2 + 1 个

#include <iostream>
#include <stdio.h>
#include <string.h>
#define LL long long
using namespace std;
const int  MAXN=1e7+5;
bool isprime[MAXN+1];
int prime[MAXN/10], tot; //防止MLE
void getPrime() {
    memset(isprime, true, sizeof(isprime));
    isprime[0] = isprime[1] = false;
    tot = 0;
    for(int i = 2; i < MAXN; i++) {
        if(isprime[i]) prime[tot++] = i;
        for(int j = 0; j < tot && prime[j] <= MAXN / i; j++) {
            isprime[i * prime[j]]=false;
            if(i % prime[j] == 0) break;
        }
    }
}
int cnt;//指数;
LL ans;
void getFactors(LL n) {
    ans=1;
    for(int i = 0; i < tot && prime[i] <= n / prime[i]; i++) {
            if(n<prime[i])break;
        if(n % prime[i] == 0) {
            cnt=0;
            while(n % prime[i] == 0) {
                cnt++;
                n /= prime[i];
            }
        }
       ans*=2*cnt+1;
    }
    if(n!=1)ans*=3;
}

int main()
{
    getPrime();
    int t;
    LL n;
    scanf("%d",&t);
    int Case=0;
    while(t--)
    {
        scanf("%lld",&n);
       getFactors(n);
       printf("Case %d: %lld\n",++Case,(ans+1)/2);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/guagua_de_xiaohai/article/details/81291582
今日推荐