数论总结

数论:研究整数规律

(待补充)

1.快速(模)幂

核心代码:

typedef unsigned long long ULL;   
ULL powermod(ULL a, ULL n, ULL m)  
{  
   ULL res = 1;  
    while(n) {  
        if(n & 1) {        // n % 2 == 1  
            res *= a;  
            res %= m;  
        }  
        a *= a;  
        a %= m;  
        n >>= 1;  
    }  
    return res;  
}  

例题链接:

HDU1420 Prepared for New Acmer【数论 快速模幂】

2.素数判定

核心代码:

int isnotprime(int n)  
{  
    if(n % 2 == 0)  
        return 1;  
  
    int end = sqrt(n), i;  
    for(i=3; i<=end; i+=2) {  
        if(n % i == 0)  
            break;  
    }  
  
    return i > end ? 0 : 1;  
}

例题链接:

HDU2012 素数判定【数论 素数判定】

3.筛选法

例题链接:

HDU5150 Sum Sum Sum【数论 筛选法】

4.模除

例题链接:

HDU2099 整除的尾数【数论 模除】

5.中国剩余定理(孙子定理)(同余方程)

6.最大公约数、最小公倍数(GCD&LCM)

核心代码:


int gcd(int m, int n)
{
    return n == 0 ? m : gcd(n, m % n);
}
 
int lcm(int m, int n)
{
    return m / gcd(m, n) * n ;
}

例题链接:

AOJ0005 GCD and LCM【数论 GCD&LCM】

7.欧几里得算法

核心代码:

int gcd(int m, int n)
{
    while(m>0)
    {
        int c = n % m;
        n = m;
        m = c;
    }
    return n;
}

例题链接:

51Nod-1011 最大公约数GCD【数论 欧几里得算法】

8.扩展的欧几里得算法

核心代码:

int exgcd(int a, int b, int &x, int &y)
{
    if (a % b == 0) {
        x = 0;
        y = 1;
        return b;
    }else {
        int r, tx, ty;
        r = exgcd(b, a % b, tx, ty);
        x = ty;
        y = tx - a / b * ty;
        return r;
    }
}

例题链接:

UVA10104 Euclid Problem【数论 扩展欧几里得算法】

9.欧拉函数

猜你喜欢

转载自blog.csdn.net/fyy_lufan/article/details/81134867