数学恒等式:1 + 3 + 5 + 7 + ... + n = ((n + 1)/2)^2
比如 1 + 3 = 4
1 + 3 + 5 = 9
1+ 3 + 5 + 7 = 16
由此可写出下面的程序:
#include<iostream>
using namespace std;
bool isSquare(int n)
{
int i = 1;
while(n > 0)
{
n -= i;
i += 2;
}
if( 0 == n)
return true;
return false;
}
int main()
{
int n;
for(n = 0; n <= 100; n++)
if(isSquare(n))
cout << n << " ";
cout << endl;
return 0;
}