简体   繁体   English

析因显示主答案错误。 功能正确计算

[英]Factorial showing wrong answer in main. Computed correctly in function

Please explain the reason for the following behavior. 请解释以下行为的原因。 Correct answer is after debug "3". 正确答案是在调试“ 3”之后。 I want that to be replicated in main after "4". 我希望将其复制到main中的“ 4”之后。

long int fact[501]={0};

long int factorial(int n)
{
    if(n==0 || n==1)
            return 1;
    if(fact[n]>1)
            return fact[n];

    if((fact[n]=n*factorial(n-1))>=1000000007)
    {       cout<<"2"<<endl<<fact[n]<<endl;
            fact[n]=fact[n]%1000000007;
            cout<<"3"<<endl<<fact[n]<<endl;
    }return fact[n];
}

int main()
{
    int n;
    cin>>n;
    cout<<"1"<<endl;
    cout<<factorial(n)<<endl;
    cout<<"4"<<endl;
    printf("%ld\n",fact[n]);
    return 0;
}

The output from the line 该行的输出

        cout<<"3"<<endl<<fact[n]<<endl;

does not necessarily correspond to n from main . 不一定对应于main n

Try this modified version to see the difference: 尝试使用此修改版本以查看不同之处:

#include <stdio.h>
#include <iostream>
using namespace std;

long int fact[501]={0};

long int factorial(int n)
{
    if(n==0 || n==1)
            return 1;
    if(fact[n]>1)
            return fact[n];

    if((fact[n]=n*factorial(n-1))>=1000000007)
    {       cout<<"2"<<endl<<fact[n]<<endl;
            fact[n]=fact[n]%1000000007;
            cout<<"3"<<endl<<n<<" "<<fact[n]<<endl;
    }return fact[n];
}

int main()
{
    int n;
    cin>>n;
    cout<<"1"<<endl;
    cout<<factorial(n)<<endl;
    cout<<"4"<<endl;
    printf("%ld\n",fact[n]);
    return 0;
}

With your compiler/platform, you have long int with 4 bytes so your value is truncated 在您的编译器/平台上,您有4个字节的long int ,因此您的值被截断了

With n >= 13 , we have n >= 13 ,我们有

fact[13] = 6227020800 which doesn't fit in a uint32_t fact[13] = 6227020800 ,它不适合uint32_t

when truncated its new value goes to 1932053504 (and then 932053497 after modulo) 截断后,其新值进入1932053504(然后932053497模后为932053497

To fix your implementation you have to use uint64_t . 要修复您的实现,您必须使用uint64_t ( https://ideone.com/gQrxyW ) https://ideone.com/gQrxyW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM