javascript - Can someone please explain this recursive JS code to calculate exponents? -


i can't understand recursion though it's simple example. when goes power(base, exponent - 1); supposed do? how things being multiplied when power keeps getting invoked until exponent equals 0?

function power(base, exponent) {     if (exponent === 0) {         return 1;     } else {         return base * power(base, exponent - 1);     } } 

let's start beginning.

let's call power(base, 0). since exponent 0, function returns 1.

now, let's call power(base, 1). since exponent isn't 0 time, function calls power(base, exponent - 1) and multiplies by base. (that's key here...it takes result recursive call, , adds own twist.) since exponent - 1 = 0, , power(base, 0) 1, result base * 1. read: base.

now on power(base, 2). ends being base * power(base, 1). , power(base, 1) base * power(base, 0). end result: base * (base * 1). read: base squared.

and on.

in case wasn't obvious, way, function work non-negative integer exponents. if exponent negative, or tiniest bit more or less whole number, function run "forever". (in reality, you'll more cause stack overflow, once recursion eats of stack.)

you fix function negative powers code like

if (exponent < 0) return 1 / power(base, -exponent); 

as non-integers...there's no way solve other throwing exception. raising number non-integer power makes sense, don't want truncate exponent or otherwise pretend didn't try -- you'd end returning wrong answer.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -