

Since the first time I used it, many, many years ago, I loved recursion. Recursion is so powerful than can give you a stack overflow (hahaha... silly joke).
I was studying some algorithms when I saw this non-recursive-but-still-pretty-cool implementation of a GCD algorithm. GCD as you know calculates the gratest common divisor between two numbers. Piece of cake, but fun to play with :)
Here is the non recursive version:
| 7 | function GCD( x, y) { |
| 8 | while(y>0) { |
| 9 | x = x%y; |
| 10 | x^=y;y^=x;x^=y; // XOR swap |
| 11 | } |
| 12 | return x; |
| 13 | } |
And here is the recursive version:
| 23 | function GCD(x,y) { |
| 24 | return (y==0)? x : GCD(y, x%y); |
| 25 | } |
As I said, I love recursion, so I will pick the second version :)
You can test both of them on tide4javascript.com, which has a pretty good step-by-step javascript debugger, alongside with a lot of algorithms you may want to study :)
Post new comment