function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) ); // 8
source = https://javascript.info/recursion
Hello all! I'm confused about the second return statement of this function:
return x * pow(x, n - 1);
I'm just looking for either some clarification or a reference to that behavior.
From my perspective, it looks like x is multiplied only by the first parameter of the function, and the n-1 is ignored.
(How does n-1 affect the result <- original question)
Sorry, I messed up the original question...
I want to ask how does javascript interprets that multiplication. When multiplying an integer and a function, I don't quite understand what's happening. How does javascript choose what to multiply with more than one parameter?
pow(2, 3) = 2 * pow(2, 2) = 2 * 2 * pow(2, 1) = 2 * 2 * 2
You are not actually calculating a product with n - 1, but refer to n as a counter. This is equivalent to
var result = 1;
while (n >= 0) {
result *= x;
n--;
}
Related
I have the following example of a recursive function, and what I don't understand is the order in which things are happening:
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
When does the function return the values, at the end of all the process or each time?
A simple way to visualize what happens in recursion in general is this:
a stack of calls to the function is created: this process needs a proper termination condition to end (otherwise you'll have infinite recursion, which is evil)
the single results are popped out of the stack: each result is used to calculate the next step, until the stack is empty
I.e. if base=5 and exponent=3, the call stack is (last element on top):
5*(5*(5*1))
5*(5*(5*power(5, 0)))
5*(5*power(5, 1))
5*power(5, 2)
power(5, 3)
then every called function has real parameters and is ready to return a value (first element on top):
5*(5*(5*1))
5*(5*5)
5*25
125
Note that here the functions are calulated in inverse order: first power(5, 0), then power(5, 1), and so on.. After each calulation an element of the stack is released (i.e. memory is freed).
Hope it helps :)
It is generally helpful in understanding recursive functions such as this to work things out like you would in an algebra class. Consider:
power(3, 4)
= 3 * power(3, 3)
= 3 * (3 * power(3, 2))
= 3 * (3 * (3 * power(3, 1)))
= 3 * (3 * (3 * (3 * power(3, 0))))
= 3 * (3 * (3 * (3 * 1)))
= 3 * (3 * (3 * 3))
...
= 81
The key here is that power is calling itself exactly in the way it could call any other function. So when it does that, it waits for the function to return and uses its return value.
So if you do
var x = power(10, 2);
Your call to power will get to this line:
return base * power(base, exponent - 1)
...and call power(10, 1), waiting for that to return.
The call to power(10, 1) will, of course, get to the line:
return base * power(base, exponent - 1)
...and call power(10, 0), waiting for that to return.
The call to power(10, 0) will return 1, which is then used by the call in #2 above to complete its work and return 10 * 1 = 10, which will then let your original call in #1 above return the value 10 * 10 = 100.
When seeking to understand things like this, there's nothing quite like walking through the code with a debugger. In this modern world, you have plenty to choose from, many of which may already be on your computer.
For better visualization, just substitute the function call with the function body (may be pseudo code for instance).
function power(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
power(5, 3) expands to this
function power(5, 3) {
// exponent 3 is not 0
// return 5 * power(5, 3-1)
return 5 * function power(5, 2) {
// exponent 2 is not 0
// return 5 * power(5, 2-1)
return 5 * function power(5, 1) {
//exponent 1 is not 0
// return 5 * power(5, 1-1)
return 5 * function power(5, 0){
//exponent 0 is 0
return 1;
}
}
}
}
Now the picture is clear. It all becomes like below..
// 1
function power(5, 3){
return 5 * function power(5, 2){
return 5 * function power(5, 1){
return 5 * ( function power(5, 0){
return 1;
} )
}
}
}
// 2
function power(5, 3){
return 5 * function power(5, 2){
return 5 * ( function power(5, 1){
return 5 * 1;
} )
}
}
// 3
function power(5, 3){
return 5 * ( function power(5, 2){
return 5 * 5 * 1;
} )
}
// 4
function power(5, 3){
return ( 5 * 5 * 5 * 1 );
}
// 5
5 * 5 * 5 * 1;
As with any recursive function, the return from a particular "instance" happens when the return value has been calculated. This means that the recursed versions will then have been calculated.
So if you pass in an exponent of 4, there will be at some point 4 copies of the function being executed at one time.
This line and its resolution really trips me up:
return base * power(base, exponent - 1)
I get that the exponent is decremented until it meets the base case, but when you mulitply
the base times the recursive function call, I keep thinking "how does the function mulitply the base by itself(the base arguement)?", where is it doing that exactly, because calling base * power(base, exponent - 1) doesn't look like the standard loop contruction. How can it be calling a function with two arguements, how does it know to skip the exponent arguement and multiply the base by the base?
From a mathematical perspective:
let x = base,
let n = exponent
x*x^(n-1) = x^n
because
x^1*x^n-1=x^n (exponents of like term adds together)
It is the same as:
base * base*exponent-1.
I am trying to find 11 power of n. I know in JavaScript there is a function Math.pow which give you power of number.I want to implement that function by own.my function is working perfectly , but its time complexity is O(n) can we reduce that time complexity using any other method?
I am thinking to use bit map, but not getting success.
function power(x,n) {
let sum =1
for(let i =0;i<n;i++){
sum*=x
}
return sum
}
console.log(power(11,3))
You could take the proposed square approach.
The complexity is O(log2(n)), like this table with the counts of the function.
n counts
------- ------
100 7
1000 10
10000 14
100000 17
function power(x, n) {
if (n === 1) return x;
let temp = power(x, n >> 1);
return n % 2
? x * temp * temp
: temp * temp;
}
console.log(power(11, 3)); // 1331 with 2 calls
One possible approach:
function power(x, n) {
let res = 1;
let acc = x;
while (n > 0) {
if (n & 1) res *= acc;
acc *= acc;
n >>= 1;
}
return res;
}
console.log(power(11, 0)); // 1
console.log(power(11, 1)); // 11
console.log(power(11, 2)); // 121
console.log(power(11, 3)); // 1331
console.log(power(11, 5)); // 161051
console.log(power(11, 8)); // 214358881 etc.
The idea is memoizing the results of subsequent squaring of the original number (x). At each step n is halved, so it's O(log n) instead of O(n). It's quite similar to #NinaScholz solution, but is iterative, not recursive (which I actually consider a benefit).
(and yes, in any real world app there should definitely be a check for MAX_SAFE_INTEGER as well, but I suppose we're discussing an algorithm here)
Here is a straightforward JS implementation of the squre approach:
function exp_by_squaring(x,n){
if(n < 0)
return exp_by_squaring(1 / x, -n);
else if(n === 0)
return 1;
else if(n === 1)
return x ;
else if(n %2===0)
return exp_by_squaring(x * x, n / 2);
else
return x * exp_by_squaring(x * x, (n - 1) / 2);
}
I also created a benchmark with some of the approaches from other answers, have a look:
Benchmark
This appears quicker than your original implementation, although not elegant
function power(x,n){
return Array.apply(null,Array(n)).reduce((r,v) => r*x, 1)
}
I am not yet able to just comment on your question but I hope I understand your question good enough. Is this something you are looking for?
const myPow = (x, y) => x ** y;
I've been trying to make a little program that can compute the n-th digit of pi.
After a few searches I've found that the most common formula is the BBP formula, wich is n-th digit = 16^-n[4/(8n + 1)-2/(8n + 4)-1/(8n + 5)-1/(8n + 6)].
The output is in base 16.
My code is the following:
function run(n) {
return Math.pow(16, -n) * (4 / (8 * n + 1) - 2 / (8 * n + 4) - 1 / (8 * n + 5) - 1 / (8 * n + 6));
}
function convertFromBaseToBase(str, fromBase, toBase) {
var num = parseInt(str, fromBase);
return num.toString(toBase);
}
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(convertFromBaseToBase(a, 16, 10));
}
So far, my output is the following:
1:3
2:0
3:0
4:0
5:1
6:7
7:3
8:1
9:7
10:3
Obviously, these are not the 10 first digits of PI.
My understanding is that values get rounded too often and that causes huge innacuracy in the final result.
However, I could be wrong, that's why I'm here to ask if I did anything wrong or if it's nodejs's fault. So I would loove if one of you guys have the answer to my problem!
Thanks!!
Unfortunately, 4/(8n + 1) - 2/(8n + 4) - 1/(8n + 5) - 1/(8n + 6) does not directly return the Nth hexadecimal digit of pi. I don't blame you, I made the same assumption at first. Although all the terms do indeed sum to pi, each individual term does not represent an individual hexadecimal digit. As seen here, the algorithm must be rewritten slightly in order to function correctly as a "digit spigot". Here is what your new run implementation ought to look like:
/**
Bailey-Borwein-Plouffe digit-extraction algorithm for pi
<https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula#BBP_digit-extraction_algorithm_for_.CF.80>
*/
function run(n) {
var partial = function(d, c) {
var sum = 0;
// Left sum
var k;
for (k = 0; k <= d - 1; k++) {
sum += (Math.pow(16, d - 1 - k) % (8 * k + c)) / (8 * k + c);
}
// Right sum. This converges fast...
var prev = undefined;
for(k = d; sum !== prev; k++) {
prev = sum;
sum += Math.pow(16, d - 1 - k) / (8 * k + c);
}
return sum;
};
/**
JavaScript's modulus operator gives the wrong
result for negative numbers. E.g. `-2.9 % 1`
returns -0.9, the correct result is 0.1.
*/
var mod1 = function(x) {
return x < 0 ? 1 - (-x % 1) : x % 1;
};
var s = 0;
s += 4 * partial(n, 1);
s += -2 * partial(n, 4);
s += -1 * partial(n, 5);
s += -1 * partial(n, 6);
s = mod1(s);
return Math.floor(s * 16);
}
// Pi in hex is 3.243f6a8885a308d313198a2e037073...
console.log(run(0) === 3); // 0th hexadecimal digit of pi is the leading 3
console.log(run(1) === 2);
console.log(run(2) === 4);
console.log(run(3) === 3);
console.log(run(4) === 15); // i.e. "F"
Additionally, your convertFromBaseToBase function is more complicated than it needs to be. You have written it to accept a string in a specific base, but it is already being passed a number (which has no specific base). All you should really need is:
for (var i = 0; i < 10; i++) {
var a = run(i);
console.log(a.toString(16));
}
Output:
3
2
4
3
f
6
a
8
8
8
I have tested this code for the first 30 hexadecimal digits of pi, but it might start to return inaccurate results once Math.pow(16, d - 1 - k) grows beyond Number.MAX_SAFE_INTEGER, or maybe earlier for other reasons. At that point you may need to implement the modular exponentiation technique suggested in the Wikipedia article.
This is a hw assignment. The answer/output I want is correct. I just don't understand why. I want the output to be true if the power function matches the number I am checking against. I do get the answer true for these examples, but I don't understand how this recursive function is working.
In the else of this function, I am saying base * the function itself. what does that even represent? How can base * power(base, exponent - 1); even compute? Shouldn't it just run in a circle and then finally end?
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
var power = function(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};
The function power returns an integer, so when the function returns base * <some_integer> is a perfectly valid expression. The best way to trace these things is with a pen and paper:
call stack of power(2,4):
power(2, 4) = 2 * power(2, 3)
power(2, 3) = 2 * power(2, 2)
power(2, 2) = 2 * power(2, 1)
power(2, 1) = 2 * power(2, 0)
power(2, 0) = 1 <--base case
now all you have to do is substitute the values up the call stack
power(2, 4) = 2 * 8 = 16
power(2, 3) = 2 * 4 = 8
power(2, 2) = 2 * 2 = 4
power(2, 1) = 2 * 1 = 2
It might help to write the function using Javascript's syntactic sugar declaration style:
console.log(power(2,4) === 16);
console.log(power(2,3) === 8);
console.log(power(2,2) === 4);
function power(base, exponent) {
if(exponent === 0) {
return 1;
}
else {
return base * power(base, exponent - 1);
}
};
If you want, you can also add the line
console.log("power("+base+", "+exponent+")");
at the head of the function, to watch the recursive call sequence.
The exponent is being reduced with each recursive call until it is equal to 0 where it will return a constant 1, and the function stops being recursive.
jsFiddle.
Also, if this wasn't homework, there is Math.pow() :)
For the example of power(2,4), we have
4 != 0 so else executes and it performs 2*power(2,3).
3 != 0 so else executes and it performs 2*power(2,2).
2 != 0 so else executes and it performs 2*power(2,1).
1 != 0 so else executes and it performs 2*power(2,0).
Finally 0 == 0 so it returns 1 and it doesnt perform another recursive call.
So it goes back through the calls and comes to 2*power(2,0) which we know power(2,0) == 1. That returns as 2.
Then it goes back to 2*power(2,1) and we know power(2,1) == 2 since [2*power(2,0)]. This returns as 4.
See the pattern? And so on until we get back to 2*power(2,3) ==16 since we have power(2,3) == 8 since [power(2,2) * power(2,1) * power(2,0) * 1]. Hope this helped!
I need to create an optimized function to count Math.pow(a,b) % c; in Javascript;
There's no problems while counting small numbers like: Math.pow(2345,123) % 1234567;
But if you try to count: Math.pow(2345678910, 123456789) % 1234567; you'll get incorrect result because of Math.pow() function result that cannot count up "big" numbers;
My solution was:
function powMod(base, pow, mod){
var i, result = 1;
for ( i = 0; i < pow; i++){
result *= base;
result %= mod;
}
return result;
Though it needs a lot of time to be counted;
Is it possible to optimized it somehow or find more rational way to count up Math.pow(a, b) % c; for "big" numbers? (I wrote "big" because they are not really bigIntegers);
Based on SICP.
function expmod( base, exp, mod ){
if (exp == 0) return 1;
if (exp % 2 == 0){
return Math.pow( expmod( base, (exp / 2), mod), 2) % mod;
}
else {
return (base * expmod( base, (exp - 1), mod)) % mod;
}
}
This one should be quicker than first powering and then taking remainder, as it takes remainder every time you multiply, thus making actual numbers stay relatively small.
Your method is good so far, but you will want to do http://en.wikipedia.org/wiki/Exponentiation_by_squaring also known as http://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
The idea is that x^45 is the same as (expanded into binary) x^(32+8+4+1), which is the same as x^32 * x^8 * x^4 * x^1
And you first calculate x^1, then x^2 == (x^1)^2, then x^4 == (x^2)^2, then x^8 == (x^4)^2, then...
you can also use the mountgomery reduction in combination with exponentiation which is largely useful for large exponents > 256:
http://en.wikipedia.org/wiki/Montgomery_reduction#Modular_exponentiation
It has also been implemented in this BigInteger Library for RSA-encryption:
http://www-cs-students.stanford.edu/~tjw/jsbn/