Have a look at my (javascript) version of a O(log(n)) xn algorithm:
function pow(x,n)
{
return n==0?1:n==1?x:n==2?x*x:pow(pow(x,(n-n%2)/2),2)*(n%2==0?1:x);
}
Can you get it shorter?
Have a look at my (javascript) version of a O(log(n)) xn algorithm:
Can you get it shorter? |
||||
If you don't mind using a global variable:
Through some ingenious trickery, Howard devised a clean alternative:
And Peter Taylor managed to shave one character:
Even shorter based on ratchet freak's idea:
|
|||||||||||||||
|
removed the replaced the used replaced |
|||
|
GolfScript (29 chars as function, 24 chars as block)
without the function wrapper that's
It's not recursive, but it is
(There is also the built-in |
||||
|
BrainFuck (482 characters) Solution is modulo 256. Reads n in digit by digit. Each time it sees a new digit d, it raises the current value to the tenth power and then multiplies that by x^d Input must be x followed by single space, followed by n, followed by newline
|
|||||
|
GolfScript - 33This feels awfully clumsy but here it goes:
Usage: (Thanks Peter Taylor) |
|||||||
|
In python we have 2 methods for doing this : def p(x,n,l): print pow(x,n,l) def p1(x,n): print x**n p(10,5,52) p1(10,5) Output corresponding to it is: 4 100000 The best part in python function is that it helps in modular power also (which is faster than finding power and then mod).In pow (n,m,l) It produces : (n^m)%l as the output. |
|||
|
Java
And if |
|||
|
x**n
– Keith Randall Mar 13 at 21:44