Hello,
I'm completely new to C++, and have tried solving the following exercise:
The integer 36 has a peculiar property: it is a perfect square, and is also the sum of the integers from 1 through 8. The next such number is 1225 which is 352, and the sum of the integers from 1 through 49. Find the next number that is a perfect square and also the sum of a series 1...n. This next number may be greater than 32767. You may use library functions that you know of, (or mathematical formulas) to make your program run faster. It is also possible to write this program using for-loops to determine if a number is a perfect square or a sum of a series. (Note: depending on your machine and your program, it can take quite a while to find this number.)
Here's what I've come up with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
int num, n = 1;
main ()
{
cout << "PERFECT SQUARES WHICH ARE ALSO THE SUM OF A SERIES 1...n" << endl <<endl;
cout << "Please press ENTER to proceed" << endl;
do
{
if (cin.get() == '\n')
{
do
{
n += 1;
num = (n * (n + 1))/2; //ensuring num is the sum of the "series n"
}
while (num != pow (ceil (sqrt (num)), 2)); //ensuring num is a perfect square
cout << "Value who's integers add up to the result (n): " << n << endl << "RESULT: " << num << endl << endl;
}
}
while (num < 2147483647);
}
|
When running it, the program works fine, up until the point where "n" reaches 131072. After that, the results are no longer correct, or at least they don't correspond to the n values. I suspect it may have something to do with the "ceil" operator which I used to make sure that num is a perfect square.
I would appreciate it if someone could point out my mistake, and maybe suggest other ways to write the program, perhaps using the methods described in the problem above.
thanks in advance!