• 1236


    1236 - Pairs Forming LCM
     

    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)'

    分析:题意1到n中存在多少对(a,b)满足lcm(a, b)==n。
    n 是a, b的所有素因子取在a, b中较大指数的积。
    将n进行素因子分解 n=a1^p1*a2^p2*...*am^pm(a1,a2,...,am均为质数),先不考虑a, b的大小,如果在a中因子a1取p1个,那么在b中a1可以取(pi-1,pi-2,...,0)个,反之一样,再加上a1在a,b中都是取p1个,所以每个素因子对应2*pi+1中情况。所以总数为 sigma(2*pi+1)/2。
    代码:

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<stack>

    using namespace std;
    typedef long long ll;
    const int maxn = 1e7+5;


    int prim[maxn/10] ;
    int k;
    int vis[maxn];

    void init() //线性筛
    {
    k = 0;
    for(int i = 2; i < maxn; ++i)
    {
    if(!vis[i]) prim[k++] = i;
    for(int j = 0; j < k && prim[j] * i < maxn; ++j)
    {
    vis[prim[j] * i] = 1;
    if(i % prim[j] == 0) break;
    }
    }
    }
    int main(void)
    {
    int T, cas;
    ll n;

    scanf("%d", &T);

    cas = 0;
    init();

    while(T--)
    {
    cas++;

    scanf("%lld", &n);
    ll ans = 1;

    for(int i = 0; i < k; i++)
    {
    ll x = 0;

    if((ll)(prim[i]) * prim[i] > n)
    break;

    while(n % prim[i] == 0)
    {
    x++;
    n /= prim[i];
    }
    if(x)
    ans *= 2 * x + 1;
    }
    if(n > 1)///n>1表示最后还剩一个素因子,比如6,20,并且这个素因子的平方大于n,再循环中没有处理。剩余最后一个因子按分析中的方法它对应三种取法,所以最后乘在ans上。
    ans *= 3;

    printf("Case %d: %lld ", cas, ans / 2 + 1);


    }

    return 0;

    }

     
  • 相关阅读:
    shell脚本程序练习
    02、重定向和管道符
    01、bash的基本特性
    python--03day
    python--02day
    python--01day
    Django之Form
    Django之ajax
    csrf的中间件
    Django之中间件
  • 原文地址:https://www.cnblogs.com/dll6/p/7682852.html
Copyright © 2020-2023  润新知