我正在尝试计算两个五角形数,它们的和与差将产生另一个五角形数。在我的主要函数中,我使用五角数定理生成五角数之和,从而产生五角数,然后使用is_pentagonal函数检查这两个数的差是否也为五角数。

我已经用C++编写了以下代码,由于某种原因,它没有给出正确的答案,而且我不确定错误在哪里。

问题是,当我得到答案d时,j和k不是五边形。 j和k仅仅超过数值极限,随机数最终产生五边形d,我不知道为什么会发生。谢谢。

bool is_perfect_square(int n)
{
        if (n < 0) return false;
        int root = sqrt(n);
        return n == root * root;
}

bool is_pentagonal(int n)
{
        if(is_perfect_square(24*n + 1) && (int)sqrt(24*n+1)%6 == 5)return true;
        return false;
}

int main() {
    int j = 0, k = 0, d = 0, n = 1;
    while(!is_pentagonal(d))
    {
        j = (3*n+1)*(3*(3*n+1)-1)/2;
        k = (n*(9*n+5)/2)*(3*n*(9*n+5)/2-1)/2;
        d = k - j;
        ++n;
    }
    cout << d << endl;
    return 0;
}

最佳答案

我已经在ideone中运行了以下代码:

#include <iostream>
#include <math.h>

using namespace std;

bool is_perfect_square(unsigned long long int n);
bool is_pentagonal(unsigned long long int n);


int main() {

    // I was just verifying that your functions are correct
    /*
    for (int i=0; i<100; i++) {
        cout << "Number " << i << " is pentagonal? " << is_pentagonal(i) << endl;
    }
    */

    unsigned long long int j = 0, k = 0, d = 0;
    int n = 1;
    while(!is_pentagonal(d))
    {
        j = (3*n+1)*(3*(3*n+1)-1)/2;
        if (!is_pentagonal(j)) {
            cout << "Number j = " << j << " is not pentagonal; n = " << n << endl;
        }
        k = (n*(9*n+5)/2)*(3 *n*(9*n+5)/2-1)/2;
        if (!is_pentagonal(k)) {
            cout << "Number k = " << k << " is not pentagonal; n = " << n << endl;
        }
        d = k - j;
        ++n;
     }

    cout << "D = |k-j| = " << d << endl;

    return 0;
}

bool is_perfect_square(unsigned long long int n) {
    if (n < 0)
        return false;
    unsigned long long int root = sqrt(n);
    return n == root * root;
}

bool is_pentagonal(unsigned long long int n)
{
    if(is_perfect_square(24*n + 1) && (1+(unsigned long long int)sqrt(24*n+1))%6 == 0)return true;
    return false;
}

结果是:
Number k = 18446744072645291725 is not pentagonal; n = 77
Number k = 18446744072702459675 is not pentagonal; n = 78
Number k = 18446744072761861113 is not pentagonal; n = 79
...

如果将这些数字与cplusplus.com所报告的2 ^ 64 = 18446744073073709551616进行比较,您会发现您与之非常接近。因此,基本上发生的是您的算法是正确的,但是数字很快变得如此之大,以至于它们溢出,然后它们就错了。请参阅here以检查您现在有哪些选项。

09-25 21:21