TLE

Hello, can somebody help me, I wrote a code that calculates a^b and then finds how many digits does that number have, but I have a problem when I put 2 numbers like
125 666 or 123456789 123456789 I get an TLE error, does anybody maybe have any ideas on how to fix it ?

#include <iostream>
#include <cmath>
using namespace std;

double long function (double long a,double long b,double long howmany,double long digits);



int main() {
double long a,b,howmany,digits;
function(a,b,howmany,digits);
return 0;

}

double long function (double long a,double long b,double long howmany,double long digits)
{
cin>>a>>b;
howmany=0;
howmany=pow (a,b);


digits=0;
while (howmany>0.99999){
howmany=1.0*howmany /10;
digits++;}
cout<<digits;


return 0;
}
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
   double a, b;
   cin >> a >> b;
   cout << (int)( 1 + b * log10( a ) ) << '\n';
}


123456789 123456789
998952458
for future reference: pow is "slow"** for integer powers. its better to write your own (the power is the key, doubles to int powers or ints to int powers either one need a hand-roll). However, as noted, you don't need the actual power for this problem -- like so many timed problems the math is more important than the coding.

**slow is in the eye of the beholder here. But if you do a few billion of them in a tight loop, you can see the problem. One at a time, its largely irrelevant. If you count the CPU clock cycles, you can see things that in terms of wall clock time are so fast that you can't even register the 'delay'.

1.0*howmany /10;
if the compiler is stupid, it may not fix the above code correctly, and do extra work.
try howmany/10.0; instead, or a cast to double. While compilers are scary smart now, they still do not catch everything and if performance matters, HELP the compiler out by not doing extra work and HOPING that it can fix your mess.

finally, you are doing what seems to mostly be integer math tricks but using doubles, and that may bite you at some point with an unexpected result.

'function' is also copying a LOT of parameters around, you may lose some time there too.
Last edited on
@Jonnin, I think the real problem here is that a number with 998952458 digits ... is simply not going to be storable as a double.
that too. but you fixed that already :)
If the OP is going to be playing with these timed contest questions -- most of the time a decent algorithm seems to pass the timer but may as well keep it tight as you go...
Last edited on
Topic archived. No new replies allowed.