|
||||||||||||
|
||||||||||||
| ||||||||||||
Hi Tim. I hope I understand what you are trying to accomplish. I will proceed with the assumption n is a non-negative integer. var p = a; // let p represent the product for (; n>0; n--) { p = p^2; } print p; This code uses the hint. When n = 0, then p = a^(2^0) which is a^1, so we start at p = a. For each higher value of n, the product is squared again. That's what is implied by the hint a^(2^(n+1)) = (a^(2^n))^2. So this little snippet of code uses a decrement loop such as one it sounds like you were leaning toward. However, the code above is not recursive; rather, it is iterative. So here's a less obvious bit of code that is recursive: // calculate p = a^(2^n) using a function that is recursive. p = f(a,n); function f(a,n) { if (n > 0) { var i = f(a,n-1); // get the value for n-1 return i*i; // and square it because a^(2^n) = [ a^(2^(n-1)) ]^2 } else { return a; // because a^(2^0) = a } } Hope this helps, | ||||||||||||
|
||||||||||||
Math Central is supported by the University of Regina and The Pacific Institute for the Mathematical Sciences. |