Convert C ++ Formula to javascript

While learning recursion, I tried to get a C ++ example function that works in javascript.

The original feature (from Stanford CS106B) is here:

int Raise (int base, int exp) { if (exp == 0) return 1; else { int half = Raise(base, exp/2); if (exp % 2 === 0) return half * half; else return base * half * half; } } Raise(3,5); 

My version below is repeated too many times. What is the main thing I messed up? I bet this is a line with var half ... I never tried to assign a function to a variable, so there is a new territory ...

 function Raise (base, expo) { if (expo === 0) return 1; else { var half = Raise(base, (expo/2)); if (expo % 2 === 0) return half * half; else return base * half * half; } } Raise(3,5); 
+4
source share
1 answer

JavaScript does not have integer division, so this line:

 var half = Raise(base, (expo/2)); 

does not do the same in JavaScript as the corresponding line in C ++. (If, for example, expo === 5 , it will return the value 2.5 for the second argument instead of the expected 2.) You can have the same effect as integer division by 2 if you use the >> operator

 var half = Raise(base, expo >> 1); 

PS I should mention that in general you can do integer division using Math.floor (or Math.ceil if the numerator and denominator have opposite signs). Bit level operators also convert their arguments to integers if necessary, so you can use ((a/b)|0) to get the integer part of the private a / b . You then do not need to worry about signs.

PPS It would probably be a little faster to use

 if ((expo & 1) === 0) 

but not

 if (expo % 2 === 0) 

check if expo even. (The situation is similar with C ++ code.)

+9
source

Source: https://habr.com/ru/post/1497740/


All Articles