总计网格中的矩形数量?

时间:2016-03-13 20:46:56

标签: c++ integer-overflow

这里我想计算M * N网格中矩形的总数。此代码工作正常,但不适用于大输入,如M = 100000 N = 100000。它显示类似-nan或任何负整数的东西。 结果将是1000000007的模数。如何在这个大的整数范围内得到准确的答案? 谢谢

#include<iostream>
#include<cmath>

using namespace std;

double factorial(int);

int main(){
  int m,n;
  double mod= 1000000007; 
    double p,q,result;
    cout << "\nPlease enter the dimensions of grid: "; 
    cin>>m>>n;
    if (m <0&&n<0)
    {
        cout << "Invalid dimensions!\n";
        return 1;
    }
    m++; n++; /*if n is the no of vertical/horizontal boxes,
                there will be n+1 vertical/horizontal lines in the grid */
    result=(factorial(m)/(2*factorial(m-2)))*(factorial(n)/(2*factorial(n-2)));
    cout<<"\nThe rectangles in the grid is:"<<fmod(result,mod);
    return 0;
}

double factorial(int x) {
    double temp;
    if(x <= 1) return 1;
    temp = x * factorial(x - 1);
    return temp;
} 

3 个答案:

答案 0 :(得分:1)

你不能在双精度数中做100000阶乘,你会得到溢出(如你所见)。

在你的情况下考虑你正在计算的扩展

 m * (m-1) * (m-2) * (m-3) * ... * 2 * 1
-----------------------------------------
         2 * (m-2) * (m-3) * ... * 2 * 1

这一切都简化为m *(m-1)/ 2.所以,你根本不需要你的阶乘函数。

编辑:另一篇文章中的代码不正确。试试这个:

result = static_cast<double>(m) * (m-1) * n * (n-1) / 4;

答案 1 :(得分:0)

与编程无关,但factorial(m)/(2*factorial(m-2)m * (m-1) / 2相同,可能不会导致溢出。

答案 2 :(得分:-1)

#include<iostream>
#include<cmath>

using namespace std;

double factorial(int);

int main(){
  int m,n;
  double mod= 1000000007; 
    double p,q,result;
    cout << "\nPlease enter the dimensions of grid: "; 
    cin>>m>>n;
    if (m <0&&n<0)
    {
        cout << "Invalid dimensions!\n";
        return 1;
    }
    m++; n++; /*if n is the no of vertical/horizontal boxes,
                there will be n+1 vertical/horizontal lines in the grid */
   //This is where I had the typo. Forgot to divide by 2.
    result=((m*(m-1))/2)*((n*(n-1))/2);
    cout<<"\nThe rectangles in the grid is:"<<fmod(result,mod);
    return 0;
}

/*double factorial(int x) {
    double temp;
    if(x <= 1) return 1;
    temp = x * factorial(x - 1);
    return temp;
} */

这应该可以正常工作。您无需实现阶乘功能。你可以简化你的陈述,你会得到你的答案。