【问题标题】:modelo of square is zero, factorial modelo problem平方模型为零,阶乘模型问题
【发布时间】:2019-12-29 06:15:08
【问题描述】:

我在做 CS 作业,问题是得到 n!,其中 n

我写了以下代码:

#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^6时,事实连续两次得到8478216162,然后是零。

提前感谢任何帮助

【问题讨论】:

  • 7+10^9 不会做你认为的那样。 ^ 是按位逻辑异或。 10^9 计算结果为 3,如果我的心算是正确的。
  • 您是否假设 7+10^9 = 1000000007 ?因为它不是。 ^ 是异或运算符
  • 你是对的,原始代码是正确的,这些是复制时的拼写错误
  • 注意fact % m在这里可以简单地替换为fact
  • 不可以,除非你的意思是n,反正我的问题还没解决

标签: c++ modulo factorial


【解决方案1】:

您的代码中有两个错误。

  1. m = 7+10^9 。这里^是指bitwise xor操作员,不是电源。你应该写m = 7 + 10e9m = 1000000007
  2. if (fact = 0) 。当您提供单个 equal 时,它不会检查。而不是将事实值分配给 0。所以写 double 相等。 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;
}

【讨论】:

猜你喜欢
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多