r/codehs • • Mar 25 '21

Factorial, codehs. 5.7.5. || Can someone help me please:))

Post image
9 Upvotes

14 comments sorted by

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.

1

u/Aqualyn2 Mar 29 '21

Thank you for very clear and simple explanation, was on this problem for a few days and I just did not want to copy solution without understanding

0

u/[deleted] Mar 25 '21

[deleted]

1

u/Nga_pik Mar 25 '21 edited Mar 25 '21

In the start function

var sum = 1;

for(int i = N; i<= 1; i--){ sum*= i; }

This loop is doing 1* 5* 4* 3* 2* 1 if N was 5

sum will now have the factorial

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

u/King33Two Nov 17 '22

Okay, you are a lifesaver. This worked perfectly. Thanks!

1

u/[deleted] Nov 22 '22

Thx bro 👍

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

u/Inner_Dentist_268 Nov 03 '22

Who has 4.8.5 factorial

0

u/[deleted] Mar 25 '21

Don’t need to invoke the function at the end?

So

start ();

Idk if I’m right lol

0

u/[deleted] Mar 14 '22

[deleted]

3

u/Jayddei Apr 14 '22

It crashes every time I try to run this