I have this simple factorial function. It works on recursion. the number that I get at the end however is NaN. I am expecting an output of 6, factorial of 3. Is the problem because I defined x as a global variable ? and if so how do you define a variable as local inside the function without making it change in recursion.
var x;
function factorial(num)
{
if (num > 0) {
x = num * factorial(num - 1);
}
return x;
}
console.log(factorial(3));
If num > 0, you define x. What is x when num is not > 0?
HINT: Should be 1. Isn't. :)
HINT2: Try console.log(1 * undefined)
P.S.: Yes, var x should go inside the function. No, it doesn't do anything bad in this case, but it could.
You need to initialize x with value first.
var x = 1;
Let's investigate detaily what happened:
f(3) = 3 * f(2);
f(2) = 2 * f(1);
f(1) = 1 * f(0);
For f(0), it directly goes to return x;, while your global variable var x; is not initialized, thus f(0) return undefined, and 1 * factorial(0) get NaN, propagates to the final result.
One solution is not to use global variable:
function factorial(num)
{
var x = 1;
if (num > 0) {
x = num * factorial(num - 1);
}
return x;
}
console.log(factorial(3)); // 6
Related
I need help creating the code to find the factorial of a number. The task is to
Create a variable to store your answer and initialize it to one
Create a loop that beings at the given value, fact
Check if fact is one or zero
multiply fact with your answer variable
At the end of the loop decrease fact
Print answer using console.log
The pseudocode is
while(factorial)
if factorial == 0 or factorial == 1
break
result => result * factorial
factorial => factorial - 1
My code below isn't complete because I'm confused by the pseudocode.
function nth_fact(nth){
var a = 1
while(nth_fact)
if (nth_fact == 0 || nth_fact == 1){
break;
result => result * nth_fact
nth_fact => nth - 1
console.log()
}
}
At first lets examine what went wrong:
var a = 1
What is a? Its definetly not a good name for a variable. Maybe name it to result ? The same applies to nth which should be named factorial and nth_fact which should rather be factorize or sth. You should also always use ; to end a statement.
while(nth_fact)
As your while loop contains multiple statements (the if and the two assignments) you need to open a block here by using { right after the condition. nth_fact refers to the function, you rather want to take factorial here.
if (nth_fact == 0 || nth_fact == 1){
break;
Now you open a block statement for the if, but you never close it. So you need another } after the break.
result => result * nth_fact
nth_fact => nth - 1
console.log()
=> is the arrow function expression, but you want the assignment operator =. Also you need to pass something to console.log, e.g. console.log(result)
All together:
function factorize(factorial){
var result = 1;
while(factorial){
if (factorial == 0 || factorial == 1){
break;
}
// ?
factorial = factorial - 1;
console.log(result);
}
return result;
}
That pseudocode is indeed confusing, because what it calls factorial is actually not the factorial -- it's the current value, which the result (which is actually the factorial we're looking for) is multiplied by. Also, if is superfluous, because while already checks for the same condition. So the correct pseudocode would be
currentValue = argument
factorial = 1
while (currentValue > 1)
factorial = factorial * currentValue
currentValue = currentValue - 1
// now, 'factorial' is the factorial of the 'argument'
Once you get this sorted out, here's a bonus assignment:
create a function range(a, b) that creates an array of numbers from a to b. For example, range(5, 8) => [5, 6, 7, 8]
create a function product(array) that multiples array elements by each other. For example, product([2, 3, 7]) => 42
write the factorial function using product and range
I solve this this way
function factorial(number) {
let num = 1;
let result = 1;
while (num <= number) {
result = result * num;
num++;
}
return result;
}
const myNumber = factorial(6);
console.log(myNumber);
function factorial(num) {
var result = 1
while (num) {
if ((num) == 0 || (num) == 1) {
break;
} else {
result = result * num;
num = num - 1;
}
}
return `The factorial of ${val} is ${result}`
}
let val = prompt("Please Enter the number : ", "0");
var x = parseInt(val);
console.log(factorial(x));
A Short And Clean Code is :
let number = 5;
let numberFactorial = number;
while(number > 1){
numberFactorial = numberFactorial * (number-1);
number--;
}
console.log(numberFactorial);
function factorize(factorial) {
if(factorial == 0 | factorial == 1) {
return 1
}
else{
var result = factorial;
while(factorial >= 1 ){
if(factorial-1 == 0) {
break
};
result = result * (factorial - 1);
factorial = factorial-1;
//DEBUG: console.log(factorial + ' ' + result);
};
return(result);
}
}
If you want more info about functions, can see in my GitHub, good learning!
Github: https://github.com/bennarthurdev/JavaScript/tree/main/FUNCOES
You used the right approach. Just the syntax was wrong. Here it is:
function nth_fact(nth){
var result = 1 ;
while(nth){
if ((nth) == 0 || (nth) == 1)
break ;
result = result * nth;
nth = nth - 1
}
console.log(result);
return result;
}
Should add all the natural numbers below 1000 that are multiples of 3 or 5.
var sum = _.reduce( _.range(1, 1000), function(x, n) {
if (n % 3 == 0 || n % 5 == 0) { return x+=n; }
}, 0);
I expect the output to be 233168 but I get NaN.
For some reason sum is not accepting the initialized value of 0. However if I preface this with var sum = 0; then it works and returns the proper output of 233168
Why doesn't it accept the initialized value?
The problem is the reducing function returns undefined when the conditional fails .. thus x evaluates to undefined (the last return value) in the subsequent invocation .. and undefined + a number is .. well, NaN.
Also, reduce is being used incorrectly; it should carry its own state. Compare it with:
var sum = _.reduce( _.range(1, 1000), function(x, n) {
// Add n to the tally if it is a valid multiple..
// (the returned value is used as the *next* value of x)
if (n % 3 == 0 || n % 5 == 0) { return x + n; }
// ..or simply return the current tally.
else { return x; }
}, 0);
Note that the sum variable was not assigned from within the reducing function (it would have been overwritten by the outside assignment anyway). This keeps reduce a pure operation, not withstanding the occasional abuse of a mutable memo, truer to its functional roots.
For example, addEventListener's 2-nd argument has a "e" or "evt" or "event" or "..." parameter. How can I add parameters to a function argument without calling it (without using arguments object). Is it possible?
Sorry for my bad english :)
You are looking for partial functions.
You can create functions with arguments and not provide them. For example,
function add(x, y) {
return x + y;
}
console.log(add(1, 2)); // 3
console.log(add(2)); // NaN (2 + undefined)
console.log(add(0)); // NaN (undefined + undefined)
If you don't want the function to return value like NaN, you can write this:
function add2(x, y) {
x = x || 0;
y = y || 0;
return x + y;
}
console.log(add2(1, 2)); // 3
console.log(add2(2)); // 2
console.log(add2(0)); // 0
I am going through the Odin Project and part of that is doing questions 1-3 in the Euler project. I am stumped on question 2:
"By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
I am so frustrated! What am I doing wrong? Here's what I have so far. Thanks!
function f() {
var fib = [];
fib.push(1,2,3);
var i = fib.length;
var total = 0;
while(fib[i] < 4000000) {
var x = fib[i-2] + fib [i-1];
if(x % 2 == 0) {
total += x;
}
} return total;
}
console.log(f());
The fibonacci sequences starts 1, 1, 2, not 1, 2, 3.
Also, your solution looks like it will work, but you are storing every number in the sequence instead of just the last two, so this will gobble memory comparatively.
As #DLeh notes, the fibonacci sequence starts with 1,1,2 - not 1,2,3. However, that doesn't change the result of summing the even valued items. The problem you're having is that at this point:
while(fib[i] < 4000000) {
fib[i] is undefined, so the function immediately exits with the total staying at 0. Also within the while loop, you're not pushing the next item in the sequence into your array. The below code fixes both of these problems:
function f() {
var fib = [];
fib.push(1,1);
var i = fib.length;
var total = 0;
while(fib[i-1] < 4000000) {
var x = fib[i-2] + fib [i-1];
fib.push(x);
i = fib.length;
if(x % 2 == 0) {
total += x;
}
} return total;
}
console.log(f()); //4613732
#DLeh also pointed out that you're storing more numbers than needed, this solution works without using the array:
function f() {
var f1 = 1;
var f2 = 1;
var total = 0;
while (f2 < 4000000) {
var t = f1 + f2;
if (t % 2 == 0)
total += t;
f1 = f2;
f2 = t;
}
return total;
}
console.log(f()); //4613732
Just for grins, note that you can do this problem without any use of %, and just + operations. Every third value in the sequence is even. That is, 2 is followed by 3 (odd), and then 3 + 2 is 5 (odd), but that sum of two odd numbers gets us back to even (8) and the cycle repeats.
Thus:
function evenFibTotal(limit) {
var a = 1, b = 1, c = 2, total = 0;
while (c < limit) {
total += c;
a = b + c;
b = a + c;
c = a + b;
}
return total;
}
On each iteration, the second trailing value is set to the next value in the sequence (b + c), and that plus the current one is the first trailing value, and finally the next even Fibonacci number is the sum of those two.
(There's also the closed solution but it's no fun :)
I'm trying to understand how recursion works in javascript. But I'm having problems even getting this function to work properly.
example problem shows calculating power and "potentially" setting the results of the calculation to innerHTML of var my header:
var myHeader= document.getElementById("myHeader");
var answer = 0;
answer = power(10, 5);
function power(base, exponent) {
if(exponent == 0)
return 0;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
Could you please edit this example code to make it work?
Example code
I just want to use chrome debuggers so I can set a breakpoint and walk through the function one by one to see the order of operations.
I'm taking this function from eloquent javascript by Marijin Haverbeke
Your power function is wrong
function power(n, p) {
if(p == 0)
{
return 1; // see Math.pow(5, 0) for example
}
return power(n, p - 1) * n;
}
and
document.getElementById('myHeader').innerHTML = power(5, 10);
You have 2 problems :
1 You used var answer = 0, you didn't assign it to get the result from power.
2 Inside your function, you returned 0 if exponent === 0, so basically, when exponent = 0, you are returning base * power(base, 0) which equals to base * 0 which in turn equals to 0, so your function will always return 0.
var myHeader= document.getElementById("myHeader");
var answer = power(10,5);
function power(base, exponent) {
if(exponent === 0)
return 1;
else
return base * power(base, exponent - 1);
}
myHeader.innerHTML = answer;
myHeader.innerHTML = power(10,5);
If you are looking for some ref parameters like in C#: function(param1, param2, ref param3), no, JavaScript has no such parameter.
If you're just looking to get the power function working, then this is a better solution:
document.getElementById("myHeader").innerHTML = Math.pow(10,5);