Reputation: 13
for int value 2,015,671 this code outputs 475,739,751
long long cube(int n)
{
return n*n*n;
}
While the correct value should be 8,189,529,329,933,957,120 but using the pow(n, 3) from <math.h> I got the correct result. If it is an overflow of long long type then why does it work for pow ? And it does not reach the MAX of long long data type 9,223,372,036,854,775,807. What is the explanation of this behaviour?
Upvotes: 0
Views: 80
Reputation: 16785
Converting the result of an expression to a new type happens too late.
If n
is an int
then n*n*n
is an expression involving only int
s and
produces an int
result (some subtle implicit conversions exist for
types smaller than int
but it is not the main concern here).
If this result overflows, then placing it in a wider integer won't help
recover the lost information.
You need to perform this conversion before computing the expression.
long long cube(int n)
{
long long r=n;
return r*r*r;
}
(or change the parameter to long long
)
Upvotes: 6
Reputation: 212
You have to explicitly cast int to long long int.
long long cube(int n) {
return (long long int) n*n*n;
}
Upvotes: 1