我正在尝试计算两个五边形数字,其和和差将产生另一个五边形数字。在我的主要功能中,我使用五边形数定理来产生五边形数,产生五边形数,然后我使用is_pentagonal函数检查这两个数字的差异是否也是五边形。
我在C ++中编写了以下代码,由于某种原因没有给出正确答案,我不确定错误在哪里。
问题是,当我得到答案时,那么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;
}
答案 0 :(得分:1)
我在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 = 18 446 744 073 709 551 616进行比较,你会发现你非常接近。所以基本上发生的事情是你的算法是正确的,但数字很快就会变得很大,然后它们就错了。请参阅here以查看您现在拥有的选项。