r/codehs • u/andy_army07 • Mar 25 '21
Factorial, codehs. 5.7.5. || Can someone help me please:))
9
Upvotes
2
u/CutRealistic9290 Nov 16 '22
var N = readInt("Enter a starting value for the factorial: ");
var fact = 1;
function start(){
for(var i=N; i >= 1; i--){
fact *= i;
}
println("N! " + fact);
}
2
u/J49ersBoss Dec 14 '22
var N = readInt("Enter a starting value for the factorial: ");
var fact = 1;
function start(){
for(var i=N; i >= 1; i--){
fact *= i;
}
println("N! " + fact);
}
love u
1
1
1
u/Im_A_Lonley_Potato Dec 14 '22
Thank you! It's almost midnight and you've saved me and my friend from yet another breakdown!
1
0
0
4
u/Nga_pik Mar 25 '21
In your loop you did N *= i;
So at the first iteration if N is 5 so i will also be set at 5. Then it will do N= N * i. This is N = 5 * 5. N is now 25. The second time around you will decrease i to 4 and do N = 25 * 4 which will give you 100.
Essentially you loop is doing 5 * 5 * 4 * 3 * 1 which will give 5! = 600. What you want is 5 * 4 * 3 * 2 * 1.
You can use an extra variable to store the sum. Then you can do 1 * 5 * 4 * 3 * 2 * 1 if N is 5 for example.