A - 费马小定理

求:3^0 + 3^1 +...+ 3^(N) mod 1000000007

Input

输入一个数N(0 <= N <= 10^9)

Output

输出:计算结果

Sample Input

3

Sample Output

40
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;
typedef long long ll;
const int maxn = 1e2 + 5;
const int INF = (1 << 30);
const double inf = 1e-6;
const int mod = 1e9 + 7;
const int MOD = 1e9 + 7;
int t, n, m, ans, cnt, cc;
int f[maxn], vis[maxn][maxn];
char mp[maxn][maxn];
struct node {
    int x, y, steps;
} no[maxn];
ll FastPow(ll n, ll k) {
    ll ans = 1;
    while(k) {
        if(k & 1) {
            ans *= n;
            ans %= mod;
        }
        k >>= 1;
        n *= n;
        n %= mod;
    }
    return ans;
}
int main() {
    scanf("%d", &n);
    ll a = (FastPow(3, n + 1) - 1 + mod) % mod;
    ll b = (FastPow(2, mod - 2)) % mod;
    printf("%lld\n", (a * b) % mod);
    return 0;
}

 

### 费马小定理的内容与数论基础 费马小定理是数论中的一个基本定理,用于描述模运算下幂的性质。其内容为:如果 $ p $ 是素数,且整数 $ a $ 与 $ p $ 互质(即 $ \gcd(a, p) = 1 $),则有: $$ a^{p-1} \equiv 1 \mod p $$ 这意味着,当 $ a $ 不是 $ p $ 的倍数时,将 $ a $ 的 $ p-1 $ 次幂对 $ p $ 取模,结果恒等于 1。例如,当 $ p=7 $、$ a=3 $ 时,$ 3^6 \mod 7 = 1 $ [^2]。 ### 应用场景与编程解释 在实际应用中,费马小定理广泛用于密码学、大数取模计算以及求解模逆元等问题。其中,模逆元的计算是一个典型应用。若要计算 $ a^{-1} \mod p $,即 $ a $ 在模 $ p $ 下的乘法逆元,可以利用以下公式: $$ a^{-1} \equiv a^{p-2} \mod p $$ 该方法仅适用于 $ p $ 为素数的情况。为了高效地计算高次幂模值,通常结合快速幂算法实现[^4]。以下是一个使用快速幂算法计算模逆元的 C++ 实现示例: ```cpp long long fastPower(long long base, long long power, long long mod) { long long result = 1; base %= mod; while (power > 0) { if (power & 1) result = (result * base) % mod; base = (base * base) % mod; power >>= 1; } return result; } long long modInverse(long long a, long long p) { return fastPower(a, p - 2, p); } ``` 通过上述代码,可以在 $ O(\log p) $ 时间复杂度内完成模逆元的计算,极大提升了效率,尤其适用于大规模数据处理和加密算法中。 此外,费马小定理还被用于生成伪随机数、优化哈希函数以及验证素数等场景,在计算机科学领域具有重要地位[^3]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值