   Polygonal Numbers
  I'm looking at a problem using polygonal numbers.  The expression to find polygonal number i in the set isi = n(3n+1)/2Going the other way, the equation to find if a number is polygonal isn = (root(24x + 1) + 1) / 6if n is natural, then x is the n'th polygonal number.I don't see how the second equation is found based on the first.I rearranged to get2i = n(3n+1) = 3n^2 + nfound the roots of that -> -1/6 += 1/6But I don't see where you'd go from there?Also, how do you check check if n is natural?  If you store it as an int, it'll be natural by default.  Should I just store as a float and call it natural provided it's natural to 4 d.p. (ie something like 5.00001) ?   
Quote:Original post by WinegumsI don't see how the second equation is found based on the first.I rearranged to get2i = n(3n+1) = 3n^2 + nfound the roots of that -> -1/6 += 1/6That's not right. The roots of that depend on the value of i.i = n(3n+1)/2 => 2i = n(3n+1) => 3n^2 + n -2i = 0 => n = (-1 +- sqrt(1 + 24i))/6So the formula you posted is correct, except for a sign. It should have beenn = (sqrt(24x + 1) -1) / 6Notice that, if n is an integer, sqrt(24x + 1) = 6n + 1 is also an integer. So the first thing you can check to determine if n is an integer is whether sqrt(24x + 1) is an integer. You can do that by rounding to the nearest integer and then computing the square of that integer, to see if you get 24x + 1 back. Once you know that it is an integer, all you have to do is check that that integer minus 1 is a multiple of 6.#include <iostream>#include <cmath>using namespace std;double round(double x) {  return floor(x+0.5);}bool is_polygonal(int x, int &n) {  int D = 24*x+1;  int sqrt_D = (int)round(sqrt(D));  if(sqrt_D*sqrt_D != D)    return false;  if((sqrt_D-1)%6 != 0)    return false;  n = (sqrt_D-1)/6;  return true;}int main() {  int x,n;    std::cout << "Enter a value for x: ";  std::cin >> x;    if(is_polygonal(x,n))    std::cout << x << " is polygonal, and the corresponding n is " << n << '\n';  else    std::cout << x << " is not polygonal\n";}