我在代码sprint5问题中实现nCr MODm时遇到问题。 链接问题是...... https://www.hackerrank.com/contests/codesprint5/challenges/matrix-tracing。 我学到的是我可以将mudular算法的规则应用于阶乘计算和逆因子计算,也可以计算pow(a,b)MODm。但我不知道我错过了什么导致了错误的答案。 这是我目前的代码。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include<math.h>
using namespace std;
const int md = 1000000007;
const int co = 2000020;
unsigned long long int ft[co];
long long int fact(unsigned long long int n)
{
return ft[n];
}
void fct(){
ft[1]=1;
for(unsigned long long int i = 2;i<=2000020;i++){
ft[i]=(i*ft[i-1]) % md;
}
}
long long int pow(long long int x, long long int n, long long int mod){
long long int result=1;
while(n>0){
if(n%2 ==1){
result = (result*x) % mod;
}
n= n>>1;
x= (x*x)% mod;
}
return result;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
unsigned long long int m , n;
long long result;
int T;
fct();
cin>>T;
while(T--){
cin>>m>>n;
unsigned long long int mod = md-2;
result = (fact(m+n-2) * pow( ( fact(m-1) * fact(n-1) ) , mod, md )) % md ;
cout<<result<<endl;
}
return 0;
}
答案 0 :(得分:1)
最后我的代码中出现了错误。
...错误
md
和co
作为无符号long long
int而不是int pow(a,b) % md
中计算pow()
.....的算法
函数,我应该先进行x % md
进一步处理
因为x的传递概率可能大于md
。目前的工作代码是.....
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>
#include<math.h>
using namespace std;
const unsigned long long int md = 1000000007;
const unsigned long long int co = 2000020;
unsigned long long int ft[co];
unsigned long long int fact(unsigned long long int n)
{
return ft[n];
}
void fct(){
ft[0]=1;
for(unsigned long long int i = 1;i<=2000020;i++){
ft[i]=(i*ft[i-1]) % md;
}
}
unsigned long long int pow(unsigned long long int x, unsigned long long int n, unsigned long long int mod){
unsigned long long int result=1;
x = x % md;
while(n>0){
if(n%2 ==1){
result = (result*x) % md;
}
n= n>>1;
x= (x*x)% md;
}
return result;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
unsigned long long int m , n;
unsigned long long int result;
int T;
fct();
cin>>T;
while(T--){
cin>>m>>n;
unsigned long long int mod = md-2;
result = (fact(m+n-2) * pow( ( fact(m-1) * fact(n-1) ) , mod, md )) % md ;
cout<<result<<endl;
}
return 0;
}