BZOJ 2818 GCD【歐拉函數】

題目鏈接:

http://www.lydsy.com/JudgeOnline/problem.php?id=2818

題意:

給定整數N,求1<=x,y<=NGcd(x,y) 爲素數的數對(x,y) 有多少對?

分析:

gcd(x,y)=p(p)(x,y)gcd(x/p,y/p)=1 的對數。那麼我們枚舉一下質數,再乘上因數的歐拉函數就好了,注意答案最後要乘上2並且要加上因數爲兩個1的情況即質數和質數本身的情況。

代碼:

/*
-- BZOJ 2818
-- Created by jiangyuzhu
-- 2016/5/29
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <stack>
#include <bitset>
using namespace std;
typedef long long ll;
#define sa(n) scanf("%d", &(n))
#define sal(n) scanf("%I64d", &(n))
#define pl(x) cout << #x << " " << x << endl
#define pr(x) cout << #x << " " << x << ' '
const int maxm = 1e7 + 5,  oo = 0x3f3f3f3f, mod = 1e9 + 7;
bool isprime[maxm];
ll phi[maxm];
int prime[maxm];
ll f[maxm];
int tot = 0;
int maxn;
void getprime()
{
    memset(isprime, true, sizeof(isprime));
    for(int i = 2; i <= maxn; i++){
        if(isprime[i]){
            prime[tot++] = i;
            for(int j = i * 2; j <= maxn; j += i) isprime[j] = false;
        }
    }
}
void euler()
{
    for(int i = 1; i <= maxn; i++) phi[i] = i;
    for(int i = 2; i <= maxn; i += 2) phi[i] /= 2;
    for(int i = 3; i <= maxn; i += 2){
        if(phi[i] == i){
            for(int j =  i; j <= maxn; j += i) phi[j] = phi[j] / i * (i - 1);
        }
    }
    f[1] = 0;
    for(int i = 2; i <= maxn; i++){
        f[i] = f[i - 1] + phi[i] * 2;
    }
}
int main (void)
{
    sa(maxn);
    getprime();
    euler();
    ll ans = 0;
    for(int i = 0; i < tot && prime[i] <= maxn; i++){
        ans += 1 + f[maxn / prime[i]];
    }
    printf("%lld", ans);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章