gpt4 book ai didi

c++ - 求 2 个五边形数,其和和差产生五边形数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:35 25 4
gpt4 key购买 nike

我正在尝试计算两个五边形数,它们的和与差将产生另一个五边形数。在我的 main 函数中,我使用五边形数定理生成五边形数和,从而生成一个五角形数,然后我使用 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
...

如果将这些数字与 2^64 = 18 446 744 073 709 551 616 进行比较,如 cplusplus.com 中所报告的那样你会注意到你非常接近那个。所以基本上发生的事情是你的算法是正确的,但数字很快变得太大以至于溢出,然后它们就错了。参见 here检查您现在有哪些选项。

关于c++ - 求 2 个五边形数,其和和差产生五边形数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com