zoukankan      html  css  js  c++  java
  • 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;

    }

     
  • 相关阅读:
    WEB安全第二篇--用文件搞定服务器:任意文件上传、文件包含与任意目录文件遍历
    WEB安全第一篇--对服务器的致命一击:代码与命令注入
    python的内存管理与垃圾回收机制学习
    java反序列化漏洞的检测
    python epoll实现异步socket
    Python class的属性访问控制和内建函数重写实现高级功能以及@property
    weblogic新漏洞学习cve-2017-10271
    PHP后门的eval类和system类 函数到底有哪些区别
    JS 转整型
    .NET MVC model数据验证
  • 原文地址:https://www.cnblogs.com/dll6/p/7682852.html
Copyright © 2011-2022 走看看