码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4983 Goffi and GCD(欧拉函数模板)

时间:2015-10-28 14:16:14      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

Problem Description:

Goffi is doing his math homework and he finds an equality on his text book: gcd(na,n)×gcd(nb,n)=n^k.

Goffi wants to know the number of (a,b) satisfy the equality, if n and k are given and 1a,bn.

Note: gcd(a,b) means greatest common divisor of a and b.
Input:
Input contains multiple test cases (less than 100). For each test case, there‘s one line containing two integers n and k (1n,k109).
 
Output:
For each test case, output a single integer indicating the number of (a,b) modulo 109+7.
 
Sample Input:
2 1
3 2
 
Sample Output:
2
1
 
Hint:
For the first case, (2, 1) and (1, 2) satisfy the equality.
 
欧拉函数(求出一个数n与1~n之间互质的个数):找到n的一个质因子i,那么1~n中与n的公约数是i的倍数的概率pi = 1/i,那么与n的公约数不是i的倍数(这些数可能就是与n互质的数)概率为1-pi,即(i-1)/i;那么当我们找到n所有的质因子时,1~n之间与n互质的概率就是所有(1-pi)的乘积,那么与n互质的个数就是:Eular(n)=n*(1-p1)*(1-p2)....(1-pi);
 
LL Eular(LL n)
{
    LL i, ans = 1;

    for (i = 2; i*i <= n; i++)
    {
        if (n % i == 0)
        {
            ans *= i-1;
            n /= i;

            while (n > 0 && n % i == 0)
            {
                n /= i;
                ans *= i;
            }
        }
    }

    if (n > 1) ans *= n-1;

    return ans;
}

此题代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

const int N=1e6+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;

typedef long long LL;

LL Eular(LL n)
{
    LL i, ans = 1;

    for (i = 2; i*i <= n; i++)
    {
        if (n % i == 0)
        {
            ans *= i-1;
            n /= i;

            while (n > 0 && n % i == 0)
            {
                n /= i;
                ans *= i;
            }
        }
    }

    if (n > 1) ans *= n-1;

    return ans;
}

int main ()
{
    LL n, k, ans, i, num;

    while (scanf("%lld %lld", &n, &k) != EOF)
    {
        ans = num = 0;

        if (k == 2 || n == 1) ans = 1;
        else if (k == 1)
        {
            for (i = 1; i*i <= n; i++)
            {
                if (n % i == 0)
                {
                    if (i*i != n) ans = (ans + Eular(n/i)*Eular(i)*2) % MOD;
                    else ans = ans = (ans + Eular(n/i)*Eular(i)) % MOD;
                }
            }
        }

        printf("%lld\n", ans);
    }

    return 0;
}

HDU 4983 Goffi and GCD(欧拉函数模板)

标签:

原文地址:http://www.cnblogs.com/syhandll/p/4917051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!