POJ 2478 欧拉函数(欧拉筛法) HDU 1576 逆元求法

相关逆元求法,我之前有写过,还有欧拉函数的求法,欧拉函数与逆元的关系  点击

POJ 2478

又是一个打表的题目,一眼看出结果就是前n个欧拉函数值的和。

这里直接计算欧拉函数值求和会超时,看见多组数据。

然后就是计算欧拉函数,打表就好了。

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 1e6 + 500;

int phi[N];
LL pre[N];
int cnt = 0;
void init()
{
    for(int i = 0; i < N; i++)
        phi[i] = i;
    for(int i = 2; i < N; i++)
    {
        if(phi[i] == i)
        {
            phi[i] = i - 1;
            for(int j = 2 * i; j < N; j += i)
                phi[j] = phi[j] / i * (i - 1);
        }
    }
    phi[1] = 0;
    memset(pre, 0, sizeof(pre));
    for(int i = 2; i < N; i++)
        pre[i] = pre[i-1] + phi[i];
}

int main()
{
    int n;
    init();
    while(scanf("%d", &n) , n)
        printf("%I64d\n", pre[n]);
    return 0;
}

HDU2478 逆元真的很常用。。而且很有用

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;

int T;
LL a, b;

void extend_gcd(LL a, LL b, LL &x, LL &y, LL &d)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        d = a;
    }
    else
    {
        extend_gcd(b, a%b, y, x, d);
        y -= (a/b) * x;
    }
}

int main()
{
    scanf("%d", &T);
    while(T--)
    {
        scanf("%lld%lld", &a, &b);
        LL x , y, d;
        extend_gcd(b, 9973, x, y, d);
        x = (x + 9973) % 9973;
        printf("%lld\n", (a*x) % 9973);
    }
    return 0;
}



posted @ 2017-07-23 22:25  可达龙  阅读(196)  评论(0编辑  收藏  举报