javascript returning infinity ( quick power ) - javascript

function pow(n,to){
if(to == 0 ) return 1;
h = pow(n,to/2);
return h*h* ((to % 2) == 0 ? 1 : n);
}
Why does this code return infinity for power different than 0?

The recursion in your function will never stop. That is because to / 2 will never be 0 when it's greater than 0. to will have these values throughout the recursion when you call it with an initial value of 10:
10 -> 5 -> 2.5 -> 1.25 -> 0.625...
You can use Math.floor() to cut off the part of a float after the decimal point. This is the function how you want it to be:
function pow(n, to) {
if (to == 0) {
return 1;
}
var h = pow(n, Math.floor(to / 2));
return h * h * ((to % 2) == 0 ? 1 : n);
}

You have infinite recursion. Meaning your function is calling itself and there is no condition to stop it from doing so. So it's calling itself forever until the javascript engine stops it. Put a console log in your function and watch it in the console.

Related

javascript explain this code function call it self

please someone explain this to me
function func(x, n) {
if (n == 1) {
return x;
} else {
return x * func(x, n - 1);
}
}
console.log(func(2, 4)); // 16
how do answer is 16
I could not understand more than this
when if is false it going to else
in the return section function call itself
at the first input is the same value as x, ie 2
at the second input is n - 1
when function run again the value of x remains the same as 2 and the value of n becomes 3
that's mean 3 times if is false
in the 4 times if if true and the execution loop ends and show answer in alert
i can not figure out what number is multiplied by x per run or the answer should be the same as 2
because every time the function is executed, shouldn't the value of x be equal to 2?
If you are asking about how recursion works, then I will explain you with this basic flowchart diagram.
I also edited your JS Code so it will provide you with clarification.
function func(x, n) {
if (n == 1) {
return x;
} else {
let function_returned = func(x, n - 1);
console.log(x, "*", function_returned, "=", x*function_returned)
return x * function_returned
}
}
console.log(func(2, 4));
The function performs exponentiation. So func(x, n) is calculating xn.
It uses recursion, based on the following principle:
When n is 1, then xn = x1 = x
When n > 1, then xn = x.xn-1
For the second statement we can use the function with arguments x and n-1.
For the concrete example, func(2, 4), this is what happens:
x=2, n=4, so we get in the else block and evaluate:
2 * func(2, 3)
For this nested call of func we have x=2, n=3, and again we get in the else block for that:
2 * func(2, 2)
And again we have a nested call, which evaluates to:
2 * func(2, 1)
...and this final nested call gets into the if block and evaluates to:
2
Now we need to backtrack as each nested function call returns the result to its caller:
2 is returned for func(2, 1) which turns 2 * func(2, 1) to 4
That 4 is returned for func(2, 2) which turns 2 * func(2, 2) to 8
That 8 is returned for func(2, 3) which turns 2 * func(2, 4) to 16
And that 16 is what you get in the output
It's a recursive power function. What it does is the following:
2^4 = ?
2 * 2^3 = ?
2 * 2 * 2^2 = ?
2 * 2 * 2 * (2^1) = ? // at this point we get to n == 1 and this is where result is just x which is 2 in your example. From this point we can start moving "back"
2 * 2 * (2 * 2) = ?
2 * (2 * 4) = ?
(2 * 8) = ?
16 = ? // 16 is just 16, we're done.
Your can read a bit about recursion to get a better idea on what is going on.

Number counts up before using an if statement to pause?

I want the number to stop when the variable num reaches a whole number. The pausing works correctly, but it goes up by 0.01 then pauses. The statement is ran every frame (via requestAnimationFrame).
if (Math.floor(num * 100) / 100 == Math.floor(num) && pause < 50) {
pause += 1;
} else {
pause = 0;
num += 0.01;
}
The complete code block is on GitHub:
https://github.com/BootLegAidan/Geometrical-Thing/blob/master/Update.js
The issue appears to be your Math.floor(num * 100 ) / 100 == Math.floor(num) condition evaluating to true even if num has a very small decimal value -- such as 1.000000007.
You can avoid that issue by comparing num to its rounded value directly:
if (num == Math.floor(num) && pause < 50) {
Compared that way, unless num is a whole number, the condition won't be true.

Can someone please explain to me how this code works?

So, a friend shared this code to me about factorials and I kind of am having a hard time understanding how it provides the correct result seeing that it didn't go through a loop. If someone could explain it to me like I'm 5 I'd really appreciate it.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
On the properties of the factorial, n! Can be written as n * (n-1) !.
That is, the result of the function for n can be obtained as n multiplied by the result of the function for n-1, and so on to 1 !:
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
The recursion basis is the value 1. And you could make the basis and 0. Then the code will be a little shorter:
function factorial(n) {
return n ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
In this case, the call factorial (1) is reduced to 1 * factorial (0), there will be an additional step of recursion.
The code is a recursive function call to get the factorial of a number.
function fact(n){ // function declaration
if(n === 1){ //strict type check if n is an integer 1 not a '1'
return 1; // return back 1
}else{ // if n is not 1
return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now.
};
};
console.log(fact(5)); //print the result of function call fact(5) and print it to console.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
It is a call which runs on the mathematical formula to calculate factorial:
n * (n-1) !
when it comes to recursion you can think of it as a function calling itself; in this case
function fact(n){
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
console.log(fact(5));
so in this case when you call fact(5)
you would get
5 * fact(5-1) = 4 * fact(4-1)= 3 * fact(3-1) = 2 * fact(2-1) = 1
resulting in 5 * 4 * 3 * 2 * 1 = 120
it's a bit tricky of a concept to figure out at first, try inserting a console.log into the function to give you a clearer picture of what's going on.
function fact(n){
console.log(n);
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}

Javascript: not grokking modulo in action

I understand the basic concept of modulo: It give you the remainder with division. I don't seem to be able to grasp how to use it correctly in practice. For instance, the following code takes a number and if it divides evenly by 2 it will return true, otherwise it returns false:
if(number % 2){
return false;
}
else{
return true;
}
It seems to me intuitively (and wrongly) that the way you would code it would be to set it so the modulo works out to 0:
if (number/2 %0) {
return true
Can anyone explain how and why the first one is correct? Keep in mind that I am obviously extremely dense ...
To check if a number divides without leaving a remainder you need to check if the result of the modulo devision is equal to zero.
if ((number % 2) == 0){
return true; // number was even
} else {
return false; // number was odd
}
From mdn % remainder documentation:
The remainder operator returns the first operand modulo the second operand, that is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables. The modulo function is the integer remainder of dividing var1 by var2.
Taking that in mind, here are the results of using % with a few values:
59 % 2
> 1
60 % 2
> 0
0 is a falsey value in javascript, so the the result of 60 %2 is never going to pass your if test. To make a proper comparison you'll need to directly check if you have a value of 0:
if (number % 2 === 0)
return true
When you use the modulo (%) operator, you are basically saying:
number % x:
Divide number by x. Round the result down to nearest integer. Multiply that integer by x. Give me the distance (absolute value) of this number to the original number.
This might not be the exact mathematical definition of modulo, but I would like to believe it is pretty close for our needs.
To give a few examples...
2 % 2 = 0 (2 / 2 = 1, 1 * 2 = 2, abs(2 - 2) = 0)
3 % 2 = 1 (3 / 2 ≐ 1, 1 * 2 = 2, abs(2 - 3) = 1)
4 % 2 = 0 (4 / 2 = 2, 2 * 2 = 4, abs(4 - 4) = 0)
The problem with your notation is that it is one extra operation that needs to be performed by the programmer. Since the current way we express the modulo operation is quite concise and does not require us to do any divisions ourselves, there is potential for performance optimisations to be done under the hood.
To express what I believe is your intent, you basically calculate the modulo with the current syntax and compare it to a particular value:
if (number % 2 === 0)
return true // Yup, its divisible by 2
Building on top of the other answers, I'd like to mention that using an if / else to explicitly return a boolean value, when you've already evaluated a boolean value, is overly verbose.
If all you are doing in the if / else is returning a boolean on either side, then your return expression can be reduced.
Good:
function isEven(num) {
return (num % 2 === 0);
}
function isOdd(num) {
return (num % 2 !== 0);
}
Bad:
function badIsEven(num) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}

What happen behind when this block of js code run?

This javaScript code block is making me crazy,that how it is doing the computation behind. I try to manually do it with calculator but the results start to be different at 4. Please explain if you know how
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
if i run console.log(fac(1));
// > 1
if i run console.log(fac(2));
// > 2
if i run console.log(fac(3));
// > 6
i was thinking this is what was happening behind
(2-1) * 2 = 2,
(3-1) * 3 = 6,
until i put
(4-1) * 4 = 12.
if i run console.log(fac(4)); the output is 24 not 12
// > 24 how and why?
cheers
It is performing recursive function call to the same function.
function fac(n) {
if (n == 0)
return 1;
else
return fac(n - 1) * n;
}
fac(4);
Value of n is 4. So it should returnfac(4 - 1) * 4). Now fac(4 -1) is calculated before returning the value.
Value of n is 3. Now it will return fac(3 - 1) * 3), which replaces fac(4 - 1) in previous statement. So, it will become fac(3 - 1) * 3 * 4.
Value of n is 2. Now it will return fac(2 - 1) * 2), which replaces fac(3 - 1) in previous statement. So, it will become fac(2 - 1) * 2 * 3 * 4.
Value of n is 1. Now it will return fac(1 - 1) * 1), which replaces fac(2 - 1) in previous statement. So, it will become fac(1 - 1) * 1 * 2 * 3 * 4.
Value of n is 0. Now it will return 1, which replaces fac(1 - 1) in previous statement. So, it will become 1 * 1 * 2 * 3 * 4.
As you can see, you can avoid multiplying by 1 twice by changing your code to
function fac(n) {
if (n == 1)
return 1;
else
return fac(n - 1) * n;
}
In short,
function fac(n) {
return (n == 1) ? 1 : (fac(n - 1) * n);
}
That's a factorial. It's calculates all permutation a set with n elements has. Or simpler:
[factorial] is the product of all positive integers less than or equal to n.
Wikipedia:Factorial
It's noted as n!. For example:
1! = 1
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6
4! = 1 * 2 * 3 * 4 = 24
What the function is doing is recursively calling itself. When you execute the function fac(4) the following happens:
At fac(4), since 4 != 0 the value returned is fac(4 -1) * 4. However, since the return function contains a reference to a function, we wait for it to return a value.
At fac(3) (i.e. fac(4-1)), since 3 != 0 the value returned is fac(3-1) * 3. However same thing happens and we wait for result of fac(3-1)/fac(2).
At fac(2) (i.e. fac(3-1)) since 2 != 0 the value returned is fac(2-1) * 2. Again, since we are calling a function we wait for its return until we proceed will calculation.
At fac(1) (i.e. fac(2-1)) since 1 != 0 the value returned is fac(1-1)* 1 and we defer for fac(1-1) to return result.
At fac(0) (i.e. fac(1-1)) since 0==0 we return value one which is neutral for multiplication.
In fac(1), fac(1-1) becomes one, so fac(1) value becomes 1*1 or 1.
In fac(2), fac(2-1) is replaced with 1 so fac(2) becomes 1*2 or 2.
In fac(3), fac(3-1) is replaced with 2, and fac(3) becomes 2*3 or 6.
In fac(4), fac(4-1) is repalced with 6 and fac(4) becomes 6*4 or 24.

Categories