平方模型为零,阶乘模型问题

modelo of square is zero, factorial modelo problem

本文关键字:模型 阶乘 问题 方模型      更新时间:2023-10-16

我正在做CS作业,问题是得到n!,其中n <=10^6,为了适合它,我需要n! % m,

我编写了以下代码:

#include <bits/stdc++.h>
using namespace std;
int main ()
{
long long n, m = 7+10e9, fact = 1;//value of m is given
cin>>n;
n++;
while (--n)
{
fact = ((fact%m)*(n%m))%m;
cout<<fact<<endl;//added this of debugging 
if (fact == 0) break;//and this also
}
cout <<fact;
return 0;
}

代码对于小数字(即 <10^5(很好,但是当数字变大时,事实输出为 0,在每一步中打印事实后,我意识到当由于某种原因 fact(x( == 事实 (x-1((x 是步骤(时,新事实为零

例如,当我输入 10^6 时,事实连续两次8478216162,然后得到零。

提前感谢任何帮助

你的代码中有两个错误。

  1. m = 7+10^9.这里的^意味着bitwise xor操作员,而不是权力。你应该把它写m = 7 + 10e9m = 1000000007
  2. if (fact = 0).当你给出单equal时,它不是检查。而不是将事实值分配给 0。所以写等于。if (fact == 0)

你的完整代码应该是这样的 -

#include <bits/stdc++.h>
using namespace std;
int main () {
long long n, m = 7+10e9, fact = 1;//value of m is given
cin>>n;
n++;
while (--n) {
fact = ((fact%m)*(n%m))%m;
//cout<<fact<<endl;//added this of debugging
if (fact == 0)
break;//and this also
}
cout <<fact;
return 0;
}