費馬小定理 幾道例題


0-1:a^(p-1)與1關於p同余

可以用來降冪

an%p=a(n%(p-1))%p;

0-2:求a的n次方,可以先n%(p-1)。

1-1 例題:

因為模數是101,比較小,而冪n是2019^2019,很大!所以使用費馬小降冪n%(p-1),這里p就是101-1 = 100;

    int n = 1, ans = 0;
    for (int i = 1; i <= 2019; i++) {
        n = n * 2019 % 100;
    }

完整代碼:

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int n = 1, ans = 0;
    for (int i = 1; i <= 2019; i++) {
        n = n * 2019 % 100;
    }
    for (int i = 1; i <= 11; i++) {
        int x = 1;
        for (int j = 1; j <= n; j++) {
            x = x * i % 101;
        }
        ans = ans + x;
    }
    printf("%d\n", ans % 101);
    return 0;
}

1-2 例題

這道題可以不用費馬小,和上題作對比

項數比mod大很多,2019比10086小,所以不用費馬小,用循環周期做

標程

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 10086;
LL pow_mod(LL x, LL p) {
    LL res = 1;
    while (p) {
        if (p & 1) res = res * x % mod;
        p >>= 1;
        x = x * x % mod;
    }
    return res;
}
int main() {
    LL ans = 0;
    LL tmp = 1e12;
    for (int i = 1; i <= mod; i++) {
        ans = (ans+pow_mod(i, 2019))%mod;//求到10086 一個循環的長度
    }
    ans = ans * (tmp / mod) % mod;//乘上倍數
    tmp %= mod;
    for (int i = 1; i <= tmp; i++) {
        ans = (ans + pow_mod(i, 2019)) % mod; //再加上余數
    }
    printf("%lld\n", ans);
    return 0;
}

2-1:其他

其他參考博客,https://blog.csdn.net/zcy_2016/article/details/55054146


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM