Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 0.60 KB  |  hits: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Efficiency of recursion vs. iteration for exponents
  2. function fastExp(base, exponent, accumulator) {
  3.   if(exponent == 0) {
  4.     return accumulator;
  5.   } else if(exponent % 2 == 0) {
  6.     return fastExp(base * base, exponent/2, accumulator);
  7.   } else {
  8.     return fastExp(base, exponent-1, base * accumulator);
  9.   }
  10. }
  11.        
  12. function fastExp(base, exponent) {
  13.   var accumulator = 1;
  14.   while(exponent != 0) {
  15.     if(exponent % 2 == 0) {
  16.       base *= base;
  17.       exponent /= 2;
  18.     } else {
  19.       exponent -= 1;
  20.       accumulator *= base;
  21.     }
  22.   }
  23.   return accumulator;
  24. }
  25.        
  26. 2^1 = 10
  27. 2^2 = 100
  28. 2^3 = 1000
  29. 2^4 = 10000