Hey everyone,
for some purpose, I need to check for large numbers if they are pentagonal. By far the fastest check is to solve the following equation:
f(x) = ( sqrt(24x + 1) + 1 ) / 2
if f(x) is an integral value, say n, then x is the nth pentagonal number.
I wrote the following function:
But this already fails for moderately large numbers due to numerical error! The function will give false, while the number entered is actually a pentagonal number.Code:bool is_pentagonal(int x) {double n = ( sqrt(24 * x + 1) + 1 ) / 2; return n == floor(n);}
My question: is there a better way of determining wether a value is integral? I searched the net for algorithms to check for perfect squares, which either used my type of method, or very complicated methods, like Newton's method (which I will dive into if I must).
Is there a simple solution (numerical or otherwise)?
Greets,
Kappie