Perfect squares which are also the sum of a series 1...n

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!
so, n=131072
(n * (n + 1))/2 = 8 billion +

But type 'int' is usually 32 bit and can only store numbers up to about 2 billion (2^31)

try making n and num to be of type double, type double can handle whole numbers up to 2^64
Last edited on
try making n and num to be of type double

No. Floating points types are not appropriate for this.

What you want is unsigned long long int. See
http://www.cplusplus.com/doc/tutorial/variables/
http://www.cplusplus.com/reference/limits/numeric_limits/

If even that range is not enough, then a custom "bigint" class is required.
Thanks a lot!

I used the unsigned long long int method, which seems to be working fine up to a certain value. After that, the result is still the sum of the series, but no longer a perfect square, for some reason.
Last edited on
Topic archived. No new replies allowed.