c++ - 反模的奇怪行为

标签 c++ primes factorial number-theory modular-arithmetic

我写了下面的代码来计算 n!modulo p...鉴于 n 和 p 很接近...但它以一种相当有趣的方式运行,无法找出错误...某处有些溢出..约束是 1 < P <= 2*10^9

1 <= N <= 2*10^9 虽然它在少数情况下运行良好......可能是什么错误。我已经使用过

(a/b)mod p = ((a mod p)*(b^(p-2))mod p)mod p

因为 p 是素数....而威尔逊定理 (p-1)! mod p = p-1

#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
unsigned int pow(unsigned int a, unsigned n,unsigned int p) {
unsigned int ret = 1;
while(n) {
if((n&1)== 1) ret=(ret*a)%p;
a=a%p;
a=(a*a)%p;
 n=n>>1;
}
return ret;
}
int main(){_
int t;
cin>>t;
while(t--){
    unsigned int n,p;
    long long int r;
    cin>>n>>p;
    r=p-1;
    if(n>=p){
        cout<<"0\n";
    }
    else{
        for(unsigned int i=p-1;i>n;i--){
            r=((long long)r*pow(i,p-2,p))%p;

        }
        cout<<r<<"\n";
    }
}   
return 0;
}

最佳答案

21!是 51090942171709440000,而 2^64 只是 1844674407370955161:所以如果 unsigned long long 是 64 位数量(很可能),它不适合。

关于c++ - 反模的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743145/

相关文章:

c++ - 通过->语法c++从指针访问函数

来自一组的 C++ 随机数

python-3.x - 高效找到一定范围内的素数

python - 在 Python3 中使用循环计算阶乘

c++ - 为什么 "decltype(i+j)"的结果不是右值引用?

c++ - 为什么线性搜索比二进制搜索快得多?

algorithm - Eratosthenes筛的引用实现

c - C 中的质因数

java - 递归教程

javascript - 阶乘乘以数字本身