 Factorial Fun - Javascript | Sololearn: Learn to code for FREE!

+3

# Factorial Fun - Javascript

The case: A number's factorial is the product of all positive integers less than or equal to the number. Write a program that takes a number as input and outputs its factorial to the console. Sample Input 5 Sample Output 120 Explanation 5*4*3*2*1 = 120 The answer: var number = parseInt(prompt()); var factorial = 1; for (; number >0; number--) { factorial=number*factorial; } console.log (factorial); I just cant understand the reason why the answer is what it is. I copied it from another post. I don't understand why we need the variable factorial So number is the input to find the factorial of the number So why do we start with a a variable called factorial. Because we always need a starting point which we can identify as 1? Why isnt the starting point actually number? as this is actually what we are stating with and using in the loop. I'm not sure if you understand what I'm trying to ask but if anyone can give more of an explanation on how the variables are decided that would be really helpful.

+3

You can go from 1 to 5 or 5 to 1. let num1 = 5; let factorial1 = 1; for(let i=1; i<=num1; i++){ factorial1 *= i; } console.log(factorial1); let num2 = 5; let factorial2 = 1; for(let i=num2; i>0; i--){ factorial2 *= i; } console.log(factorial2); Both will give the same result. Yes you need to store the multiples of the values somewhere and thereby you need a variable which is factorial in this case.

+1

The variable "factorial" is assigned the product of iterations of the variable "number", which decreases by 1 with each iteration. f = n * f => f = 5 * 1 = 5 f = 4 * 5 = 20 f = 3 * 20 = 60 And so on, until "number" becomes "0". The expression f = n * f can be abbreviated f *= n

+1

Thanks for all of your help. Still in the very early days of trying to get my head around the programming. I understand the code but actually applying it is tough!

0

Because you need two different variables. Without that, it would look something like this: number = prompt() for (; number > 0; number--) { number *= (number-1); } Imagine the user inputs 3 as the number. Then number is multiplied by 2, so now number is 6. Then number is reduced by 1 for the next iteration. Now it is 5 and multiplied by 4, so it is 20. As you can see, number will get higher and higher and thus the for loop will never end. Two variables mean you have one variable keeping track of the product up to now, and another one to keep track of which is the next number to multiply to it.

0

'factorial' variable is here to hold the result... it is initialized with 1 because 1 multply anything == anything... you could loop only from 2 to number, as if number == 1, the loop won't be executed, and result will be 1, and if number > 1, skipping 1 didn't makes change to the result ;)

0

hold tight ;) it should becomes more and more obvious with time and practices ;)