+ 4

Challenge: you can code, but can you can efficiently ?

Using only basic operations (+ - * /) code a fastexp function returning x^p using the smallest possible number of basic operations for any p<1000.

10th Aug 2017, 9:32 PM
VcC
VcC - avatar
9 Respuestas
10th Aug 2017, 10:40 PM
Maz
Maz - avatar
10th Aug 2017, 9:59 PM
Sivan Tal
Sivan Tal - avatar
+ 2
My previous solution, while better than others, was still not optimal, and had O(p) complexity in average case. I found a better solution which really gives O(log(p)). The following code includes the original solution plus the more efficient code. It also measures and prints the efficiency of the two. In SoloLearn env the time calculations don't work, but it still counts the number of operations. In regular OS it also shows the actual time it took. https://code.sololearn.com/c72gCKYe1M3l
12th Aug 2017, 3:46 PM
Sivan Tal
Sivan Tal - avatar
+ 1
In C++ : x is a decimal number positive or negative, p is an integer positive or negative. https://code.sololearn.com/cmBJl9657C5x/?ref=app
10th Aug 2017, 10:44 PM
Jojo
0
Sivan's solution is the best so far, but you can do a little bit better ! Maz and Jojo : if p=999 you do 999 multiplications...
11th Aug 2017, 4:16 AM
VcC
VcC - avatar
0
This is a good example of how a good algorithm even with a slow language (Python) can be faster than an average algorithm with a fast language (C++ or any compiled language or even assembler). Nb: >> and & are usually faster than * https://code.sololearn.com/cWqyF1QagEm1/?ref=app
11th Aug 2017, 4:40 AM
VcC
VcC - avatar
- 1
The recursion might look elegant but it runs VERY slowly... Just run the following code to see how much. Also this code proposes a faster version relying on binary operations (<< &) which are usually much faster https://code.sololearn.com/cn4f5No80UvM/?ref=app
12th Aug 2017, 12:16 PM
VcC
VcC - avatar
- 1
What is funny too is that logarithmic algorithms can lose against naive ones depending on how they are implemented....
12th Aug 2017, 2:31 PM
VcC
VcC - avatar
- 1
Also with p=1000 a logp algo with a big constant ( is C.logP) can be slower than a very 'dry' P
12th Aug 2017, 3:45 PM
VcC
VcC - avatar