what's wrong ?!

ok so.... I have this formula: T(n) = n(n+1)/2

where n = 123456789.

I have to calculate sum of digits of T(n).

1
2
long long int T = (123456790 / 2 ) * 123456789;
cout << sumOfdigits(T);


and sumOfdigits(T) return the sum of digits of parameter.

it's shows me 33 as a result, which is obviously wrong !
showing your sumOfdigits() method might help..
1
2
3
4
5
6
7
8
9
10
11
int sumOfdigits( long long int y)
{
   long long  int sum = 0;
    while(y!=0)
    {
        sum = sum + (y%10);
        y = y /10;
    }

    return sum;
}
integer division issues maybe?
also you're return value from that function is an int, yet you're returning a long int int ('sum').
Last edited on
I suspect you're overflowing the domain of a long long int. Try printing T right after you compute it.
I print T and it is 1330264167.
And the sum of digits is 33, but it says me that the answer is wrong !

I will copy paste the problem:

A triangle number is computed with the following formula:
T(n) = n(n+1)/2
Using the above formula, the first 5 triangle numbers are:

1 3 6 10 15 ...
What then is the sum of the digits of the 123,456,789th triangle number?

1
2
3
4
5
{
  unsigned long long int T = (123456790 * 123456789) /2;
    cout << T << " \n";
    cout << sumOfdigits(T);
}


now it shows me 83, and alos it says it is wrong !
http://www.cplusplus.com/forum/general/112111/#msg612042
warning: integer overflow in expression [-Woverflow]
unsigned long long int T = (123456790 * 123456789) /2;


123456789ull (or make yourself a favor and assign it to a variable)
Last edited on
Also, is the number you're look at 123456789 or 123456790?:
1
2
3
4
5
{
  unsigned long long int T = (123456790 * 123456789) /2;
    cout << T << " \n";
    cout << sumOfdigits(T);
}
Last edited on
the formulae uses n*(n+1)
n is 123456789
Okay, the problem is that (123456790 * 123456789) /2 is an integer expression. This overflows. The overflowed value is then used to initialize the long long T.

To fix it, you have to ensure that the right side uses long long arithmetic. You can do this by forcing the first item to be a long long:
long long int T = (123456790LL / 2 ) * 123456789;

The long long problem and my question about the constants would both go away if you let the compiler do all the arithmetic. This would also make it much easier to read:
1
2
const long long N = 123456789;
long long int T = N * (N+1) / 2;
thank you dhayden !

now it works !
Topic archived. No new replies allowed.