It tried to solve this problem, given N,K amd M
, find maximum integer T
such that N*(K^T) <= M
. N,K and M
can be the values to 10^18
. So long long
is sufficient.
I tried to solve it using iteration on T
int T = 0;
long long Kpow = 1;
while(1)
{
long long prod = N*Kpow;
if(prod > M)
break;
T++;
Kpow = Kpow*K;
}
But since N*Kpow
may go out of range of long long
, there is need to handle the product using some big integer. But I found some other code which smartly handles this case
long long prod = N*Kpow;
if(prod < 0)
break;
Even I have seen always, that in overflow, the value of variable becomes negative. Is it always the case or sometimes even positive values also occur in overflow case?
From the point of view of the language, the behaviour of signed integer overflow is undefined. Which means anythign could happen - it can be negative, it can be unchanged, the program can crash or it can order pizza online.
What will most likely happen in practice depends on the processor architecture on which you're running - so you'd have to consult the platform specs to know.
But I'd guess you can't guarantee overflow to be negative. As a contrived example:
signed char c = 127;
c += 255;
std::cout << (int)c << '\n';
This happens to print 126
on x86. But again, it could actually do anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With