GCD - Extreme (II) UVA - 11426(欧拉函数运用)

题目链接
Given the value of N, you will have to find the value of G. The definition of G is given below:

在这里插入图片描述
Here GCD(i, j) means the greatest common divisor of integer i and integer j.
For those who have trouble understanding summation notation, the meaning of G is given in the
following code:
G=0;
for(i=1;i<N;i++)
for(j=i+1;j<=N;j++)
{
G+=gcd(i,j);
}
/Here gcd() is a function that finds
the greatest common divisor of the two
input numbers
/
Input
The input file contains at most 100 lines of inputs. Each line contains an integer N (1 < N < 4000001).
The meaning of N is given in the problem statement. Input is terminated by a line containing a single
zero.
Output
For each line of input produce one line of output. This line contains the value of G for the corresponding
N. The value of G will fit in a 64-bit signed integer.
Sample Input
10
100
200000
0
Sample Output
67
13015
143295493160
**题意:**给定N,求∑i<=ni=1∑j<nj=1gcd(i,j)的值。

**思路:**lrj白书上的例题,设f(n) = gcd(1, n) + gcd(2, n) + … + gcd(n - 1, n).这样的话,就可以得到递推式S(n) = f(2) + f(3) + … + f(n) ==> S(n) = S(n - 1) + f(n);.
这样问题变成如何求f(n).设g(n, i),表示满足gcd(x, n) = i的个数,这样f(n) = sum{i * g(n, i)}. 那么问题又转化为怎么求g(n, i),gcd(x, n) = i满足的条件为gcd(x / i, n / i) = 1,因此只要求出欧拉函数phi(n / i),就可以得到与x / i互质的个数,从而求出gcd(x , n) = i的个数,这样整体就可以求解了

#include <iostream>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <cstdlib>
#include <iomanip>
#include <string>
#include <queue>
#include <map>

using namespace std;
typedef long long ll;

#define maxn 4000005
#define INT __int64
ll Prime[maxn+1];
ll ans[maxn+1];
ll b[maxn+1],dp[maxn+1];

void prime()//素数表0是素数1为合数
{
    memset(Prime,0,sizeof(Prime));
    Prime[0]=Prime[1]=1;
    for(int i=2;i*i<=maxn;++i)
    {
        if(!Prime[i])
        {
            for(int j=i*i;j<=maxn;j+=i)
                Prime[j]=1;
        }
    }
}
void eulerfun()//欧拉表
{
    for(int i=1;i<=maxn;++i)
        ans[i]=i;
    for(int i=2;i<=maxn;i++)
    {
        if(!Prime[i])
            for(int j=i;j<=maxn;j+=i)
                ans[j]=ans[j]/i*(i-1);
    }
}
int main()
{
    int n;
    prime();
    eulerfun();
    for(int i=1;i<maxn;++i)//[1,n-1]中所有的数与n的gcd的和
        for(int j=i*2;j<maxn;j+=i)
            b[j]+=ans[j/i]*i;
    for(int i=2;i<maxn;i++)
        dp[i]=dp[i-1]+b[i];
    while(~scanf("%d",&n)&&n)
        printf("%lld\n",dp[n]);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值