How to get Factorial of number in JavaScript? [duplicate] - javascript

This question already has answers here:
What is the fastest factorial function in JavaScript? [closed]
(49 answers)
Closed 7 years ago.
I'm learning Java Script and there is an exercise about getting the factorial of number user has entered but for some reason I always get answer is = 1
here is my code :
<SCRIPT>
function factorial(num){
for (n=1; n<=num; n++){
return fact*n;
}
}
var myNum, fact;
myNum = parseFloat(window.prompt('Enter positive integer : ',''));
fact = 1;
document.write('the factorial of the number is = '+ factorial(myNum));
</SCRIPT>

The pictured code (please include actual code in the future, not screenshots of code) returns fact immediately:
for ( n = 1; n <= num; n++ ) {
return fact * n;
}
since n starts at 1.
What you want is to include fact in the function, and multiply it as the loop goes along, then return:
function factorial(n) {
var fact = 1;
for ( n = 2; n <= num; n++ ) {
fact = fact * n;
}
return fact;
}

The reason this is returning 1 is because in your loop above, you return the value on the very first iteration, so n is never greater than 1.

Related

javascript external called function does not return value [duplicate]

Im solving a codewars problem and im pretty sure i've got it working:
function digital_root(n) {
// ...
n = n.toString();
if (n.length === 1) {
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
//console.log(count);
digital_root(count);
}
}
console.log(digital_root(942));
Essentially it's supposed to find a "digital root":
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n. If that value has two
digits, continue reducing in this way until a single-digit number is
produced. This is only applicable to the natural numbers.
So im actually getting the correct answer at the end but for whatever reason on the if statement (which im watching the debugger run and it does enter that statement it will say the return value is the correct value.
But then it jumps out of the if statement and tries to return from the main digital_root function?
Why is this? shouldn't it break out of this when it hits the if statement? Im confused why it attempt to jump out of the if statement and then try to return nothing from digital_root so the return value ends up being undefined?
You're not returning anything inside else. It should be:
return digital_root(count);
^^^^^^^
Why?
digital_root is supposed to return something. If we call it with a one digit number, then the if section is executed, and since we return from that if, everything works fine. But if we provide a number composed of more than one digit then the else section get executed. Now, in the else section we calculate the digital_root of the count but we don't use that value (the value that should be returned). The line above could be split into two lines of code that makes it easy to understand:
var result = digital_root(count); // get the digital root of count (may or may not call digital_root while calculating it, it's not owr concern)
return result; // return the result of that so it can be used from the caller of digital_root
Code review
My remarks is code comments below
// javascript generally uses camelCase for function names
// so this should be digitalRoot, not digital_root
function digital_root(n) {
// variable reassignment is generally frowned upon
// it's somewhat silly to convert a number to a string if you're just going to parse it again
n = n.toString();
if (n.length === 1) {
// you should always specify a radix when using parseInt
return parseInt(n);
} else {
let count = 0;
for (let i = 0; i < n.length; i++) {
//console.log(parseInt(n[i]))
count += parseInt(n[i]);
}
// why are you looping above but then using recursion here?
// missing return keyword below
digital_root(count);
}
}
console.log(digital_root(942));
Simple recursive solution
With some of those things in mind, let's simplify our approach to digitalRoot...
const digitalRoot = n =>
n < 10 ? n : digitalRoot(n % 10 + digitalRoot((n - n % 10) / 10))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
Using reduce
A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
If you are meant to use an actual reducing function, I'll show you how to do that here. First, we'll make a toDigits function which takes an integer, and returns an Array of its digits. Then, we'll implement digitalRoot by reducing those those digits using an add reducer initialized with the empty sum, 0
// toDigits :: Int -> [Int]
const toDigits = n =>
n === 0 ? [] : [...toDigits((n - n % 10) / 10), n % 10]
// add :: (Number, Number) -> Number
const add = (x,y) => x + y
// digitalRoot :: Int -> Int
const digitalRoot = n =>
n < 10 ? n : digitalRoot(toDigits(n).reduce(add, 0))
console.log(digitalRoot(123)) // => 6
console.log(digitalRoot(1234)) // 10 => 1
console.log(digitalRoot(12345)) // 15 => 6
console.log(digitalRoot(123456)) // 21 => 3
console.log(digitalRoot(99999999999)) // 99 => 18 => 9
its a recursive function the code should be somewhat like this
function digital_root(n) {
// ...
n=n.toString();
if(n.length === 1){
return parseInt(n);
}
else
{
let count = 0;
for(let i = 0; i<n.length;i++)
{
//console.log(parseInt(n[i]))
count+=parseInt(n[i]);
}
//console.log(count);
return digital_root(count);
}
}
you should return the same function instead of just calling it to get the correct call stack

JavaScript Function. Can someone help or explain why it logs 120? I see 20 based on my analysis [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I would like to sum up all the elements inside the array covertedValue. Why I am getting a Nan result? whats wrong with the recursive function I have written?
function findOutlier(integers){
var covertedValue = integers.map(x => x % 2);
var total = 0;
for (i=0 ; i<covertedValue.length ; i++){
total = total + covertedValue[0] + findOutlier(integers.splice(1));
}
console.log(total);
}
findOutlier([0, 1, 2]);
because this line create a function and a private alias to itself
var factorial =
// create a variable named factorial in global scope
// it contains the function fac
function fac(n) {
// fac is a function available only in the factorial var context
return n < 2 ? // if n < 2
1 : // return 1
n * fac(n - 1); // else return n * fac(n - 1)
};
console.log(factorial(5));
// calls factorial(5) which is 5*fac(4) which is 5*(4*fac(3)) ...
note that the fac function is not available outside of itself
var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); };
console.log(fac(5));
This way of coding where a function call itself is called recursive programming it can be hard to grasp at first but can be VERY powerful in some situations
recurcive programming can easily be used when the result of func(n) depend directly on the result of func(n+x)
the cond ? then : else structure is called ternary operator, it's a way to make if in one line, can become messy very quick
as you noted in a comment : recursion can be replaced by a loop (it can be hard to do it sometime)
here's a more beginner way to write it
function factorial(n) {
if(n < 2) {
return 1
} else {
let fac = 1;
for(var i = n; i > 0; i--) {
fac = fac * i
// here fac takes the value of the precedent iteration
}
// this whole loop is the same as i*fac(i-1) in the recurcive way
return fac
}
};
console.log(factorial(5));

C++ to javascript conversion

The question I'm doing is:
Write a JavaScript program to create a function which returns the number of times required to replace a given number with the sum of its digits until it converts to a single digit number. Like if given number is 123, number of times required to convert it into a single digit number is 1 (1+2+3=6). Your output code should be in the format console.log("Result is ", variableName)
I could not find the solution to this problem so I googled it and found this page.
The code on this page is in C/C++ ,Java etc...I took the C++ code and tried to convert it to javascript myself and this is the result:
var num=prompt("Enter a number");
var a= num.toString();
function test(x)
{var temporary_sum = 0, count = 0;
while (x.length() > 1)
{
temporary_sum = 0;
// computing sum of its digits
for (var i = 0; i < x.length(); i++)
temporary_sum += ( x[ i ] - '0' ) ;
// converting temporary_sum into string
// x again .
x = temporary_sum.toString() ;
// increase the count
count++;
}
return count;
}
var output = test(a) ;
console.log("Result is: ", output);
This code does not give any output at all. How can I fix this? Is there a better way to do this question?
Here is a better way to do that using recursion. And reduce
function test(x,count=0){
if(String(x).length === 1) return count;
let sum = String(x).split('').reduce((ac,a) => Number(a) + ac,0);
return test(sum,++count);
}
console.log(test(123)) //1
console.log(test(456)) //2
console.log(test(99999999999)) //3
I'll answer your last question - yes, there is a better way to do this question. You want to use recursion. You can also split the string on '' to convert its digits into an array, and you want to use parseInt to turn it back into a number.
I will use a different approach (I don't say it would be better). First, I will skip the mapping from number to string and wraps the logic that sums the digits of some number into a function called sumDigits(). This way you have a resusable method you can use for other purposes later. The second step is to define your test function using the previously created sumDigits mainly using the while loop you already have but testing with another condition and generalized to accept also integer negative numbers:
const sumDigits = (num) =>
{
let sum = 0;
while (num)
{
sum += num % 10, num = Math.floor(num / 10);
}
return sum;
}
const test = (num) =>
{
let counter = 0;
num = Math.abs(num);
while (num >= 10)
{
num = sumDigits(num), counter++;
}
return counter;
}
console.log(test(123));
console.log(test(456));
console.log(test(-789));

Recursive Function not returning value as expected [duplicate]

This question already has answers here:
Recursive function does not return specified value
(2 answers)
javascript return of recursive function
(4 answers)
Closed 4 years ago.
In this function i am trying to calculate the number of ways, a number can be decoded. 1 ought to be decoded as a, 3 as c, 26 as z .
The function calculates the right count, but does only return undefined.
I think it should cancel the recursive calls at the right time, and I reach the "escape"-block, but the number is not returned as it should.
Can anyone point me towards the reason, why this is happening?
function numWaysDecodable(msg) {
msg = msg.toString().split("");
function helper(msg, past = 99, count = 1) {
if (msg.length === 0) {
console.log("wtf count is:"+count);
return count;
}
let head = msg.shift();
if (head < 7 && past < 3) {
count++
}
//the below return statement was missing
return helper(msg, head, count);
}
return helper(msg);
}
console.log(numWaysDecodable(123));
The fixed code is still faulty, as the algorithm is flawed for other input.
For example for the input 1212 we return 4, even though we should recieve the result 5:
12 1 2;
1 2 12;
12 12;
1 2 1 2;
1 21 2;
I think the code misses to count nr.3,12 12; I am unsure how to fix that as of yet. Some more thinking to do
You have to return value in each call of the recursive function like:
return helper(msg, head, count);
function numWaysDecodable(msg) {
msg = msg.toString().split("");
function helper(msg, past = 99, count = 1) {
if (msg.length === 0) {
console.log("wtf count is:"+count);
return count;
}
let head = msg.shift();
if (head < 7 && past < 3) {
count++
}
return helper(msg, head, count);
}
return helper(msg);
}
console.log(numWaysDecodable(123));

How works multiplication just after incrementation (i++ * 2) in Javascript? [duplicate]

This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 8 years ago.
Please read whole topic, before post answer. No answer found to this question in post: ++someVariable Vs. someVariable++ in Javascript
var i = 1;
i = i++ * 2; // i = 2, .. why not 4 ?
interpreter does the multiply (1*2), but where is the increment ( i++ )?
var i = 1;
i = ++1 * 2; // i = 4
I'm understand, that the i++ does the increment after the statement, ++i does it before the statement, but in this example: i = i++ * 2 // (1*2), how the interpreter works?, where is the increment of i in this case? maybe i = (1*2)+1 )), or i = (1*2) and no more i exist, and nothing to increment??
HOW ?
P.S. I think, it is a wrong question, but as Brooks Hanes said(in comment), this is a learning example.
i++ means: read the value of variable i, then increase variable i
++i means: increase variable i, then read the value of variable i
This is an interesting little problem, a simple experiment shows what is happening. jsFiddle
var i = 3; p = i++ *2; console.log(i, p);
The 2 is multiplied by i (3) the result (6) is placed in p. Then a copy of the original value of i (3) is incremented and placed back in i. This behaviour is logically consistent with the following:
var i = 3; var p = 0; function adder(x) { p = x + 2; }; adder(i++); console.log(i, p);
This makes a strange kind of sense because the post increment is supposed to happen after the statement.

Categories

Resources