I am trying to calculate two pentagonal numbers whose sum and difference will produce another pentagonal number. In my main function I use pentagonal number theorem to produce pentagonal number sums that produce a pentagonal number and then I check if the difference of those 2 numbers is also pentagonal using is_pentagonal function.
I've written the following code in C++ and for some reason in doesn't give the correct answer and I'm not sure where the mistake is.
The thing is, when I get my answer d then j and k are not pentagonal. j and k simply go above the numerical limit and random numbers eventually produce pentagonal d and i don't get why it happens. Thank you.
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;
}