• 数论模板


    #include <cstdio>
    #include <cmath>
    #include <cstring>
    
    using namespace std;
    
    const int maxn = 105;
    
    int n;
    
    int vis[maxn], prime[maxn], phi[maxn];
    
    void sieve(int n)
    {
        int m = (int) sqrt(n + 0.5);
        memset(vis, 0, sizeof vis);
        for (int i = 2; i <= m; i++) if (!vis[i])
            for (int j = i * i; j <= n; j += i) vis[j] = 1;
    }
    
    int get_primes(int n)
    {
        sieve(n);
        int c = 0;
        for (int i = 2; i <= n; i++) if (!vis[i])
            prime[++c] = i;
        return c;
    }
    
    int gcd(int a, int b)
    {
        return b == 0 ? a : gcd(b, a % b);
    }
    
    void ex_gcd(int a, int b, int d, int& x, int& y)
    {
        if (!b) 
        {
            d = a;
            x = 1;
            y = 0;
        }else
        {
            ex_gcd(b, a % b, d, y, x);
            y -= x * (a / b);
        }
    }
    
    int ksm(int a, int b, int M)
    {
        int ans = 1, base = a;
        while (b)
        {
            if (b & 1)
                ans = (ans *  base) % M;
            base = (base * base) % M;
            b >>= 1;
        } 
        return ans % M;
    }
    
    int euler_phi(int n)
    {
        int m = (int)sqrt(n + 0.5);
        int ans = n;
        for (int i = 2; i <= m; i++) if (n % i == 0)
        {
            ans = ans / i * (i - 1);
            while (n % i == 0) n /= i;
        }
        if (n > 1) ans = ans / n * (n - 1);
    }
    
    void phi_table(int n)
    {
        for (int i = 2; i <= n; i++) phi[i] = 0;
        phi[1] = 1;
        for (int i = 2; i <= n; i++) if (!phi[i])
        {
            for (int j = i; j <= n; j += i)
            {
                if (!phi[j]) phi[j] = j;
                phi[j] = phi[j] / i * (i - 1);
            }
        }
    } 
    
    int main()
    {
        scanf("%d", &n);
        printf("%d
    ", get_primes(n));//求质数 
        for (int i = 2; i <= n; i++)
            if (!vis[i])
                printf("%d ", i);
        int x, y;
        printf("
    ");
        scanf("%d%d", &x, &y);
        printf("%d
    ",gcd(x, y));//求gcd 
        int a, b, d;
        x = y = 0;
        scanf("%d%d", &a, &b);
        ex_gcd(a, b, d, x, y);//求ex_gcd 
        printf("%d %d
    ", x, y);
        int M;
        scanf("%d%d%d", &a, &b, &M);//求a^b mod M; 
        printf("%d
    ", ksm(a, b, M));
        scanf("%d", &n);
        printf("%d
    ", euler_phi(n));
        phi_table(n);
        for (int i = 1; i <= n; i++)
            printf("%d ", phi[i]);
        return 0;
    }
  • 相关阅读:
    1046 A^B Mod C
    1019 逆序数
    1012 最小公倍数LCM
    1011 最大公约数GCD
    序列化
    bigdecimal
    equals 和hashcode
    java多线程-读写锁原理
    Java并发编程:volatile关键字解析
    面试
  • 原文地址:https://www.cnblogs.com/yohanlong/p/7774780.html
Copyright © 2020-2023  润新知