GCD - Extreme (II) UVA - 11426(gcd+欧拉函数)

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:
G = i<Ni=1j<=Nj=i+1 ∑ i = 1 i < N ∑ j = i + 1 j <= N GCD(i,j)

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 correspondingN. The value of G will fit in a 64-bit signed integer.
  
Sample Input
10
100
200000
0
Sample Output
67
13015
143295493160

题意:

给定N,求所给公式的值

分析:

由给出到公式,我们设 f(n)=gcd(1,n)+gcd(2,n)+gcd(3,n)+......+gcd(n1,n) f ( n ) = g c d ( 1 , n ) + g c d ( 2 , n ) + g c d ( 3 , n ) + . . . . . . + g c d ( n − 1 , n )
同理 f(n1)=gcd(1,n)+gcd(2,n)+...+gcd(n2,n1) f ( n − 1 ) = g c d ( 1 , n ) + g c d ( 2 , n ) + . . . + g c d ( n − 2 , n − 1 )
.
.
.
f(2)=gcd(1,2) f ( 2 ) = g c d ( 1 , 2 )
所以公式求和 G=S(n)=f(2)+f(3)+...+f(n) G = S ( n ) = f ( 2 ) + f ( 3 ) + . . . + f ( n )
所以我们到任务变成求 f(n) f ( n )

为了便于说明我们再设一个变量叫 g(n,j) g ( n , j ) ⟶ 满足 gcd(x,n)=j g c d ( x , n ) = j 到个数,其中x是[1,n]的数

gcd(xj,nj)=1 g c d ( x j , n j ) = 1 ,问题再次简化,设 i=nj i = n j ,我们只要找到i以内和i互质到个数即可,这样我们枚举倍数j只要i×j < n 即可,而这个倍数就是上面到最大公因数。
这样我们就相当于知道了和n公因数为j到个数一乘便是和即
f(n)=(jg(n,j)) f ( n ) = ∑ ( j ⋅ g ( n , j ) )
求一个数以内互质到个数用欧拉函数即可

code:
#include <bits/stdc++.h>
using namespace std;
const int N = 4e6+10;
typedef long long ll;
int phi[N];
ll f[N];
void getphi(){
    for(int i = 1; i < N; i++) phi[i] = i;
    for(int i = 2; i < N; i++){
        if(phi[i] == i){
            for(int j = i; j < N; j += i){
                phi[j] = phi[j] / i * (i - 1);
            }
        }
        for(int j = 1; j * i < N; j++){
            f[j*i] += j * phi[i];
        }
    }
}
int main(){
    getphi();
    int n;
    while(cin >> n && n){
        ll ans = 0;
        for(int i = 1; i <= n; i++){
            ans += f[i];
        }
        printf("%lld\n",ans);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值