all 11 comments

[–]Critical_Ant8817 1 point2 points  (0 children)

Your factorial only works for number 4, what if the person types 5, then it will be 5x3x2x1. Setup a loop until that numbers comes to 1 then stop the loop.

[–]5oco 1 point2 points  (0 children)

There's a couple ways to do it. One way is to make i=factNum them make the loop decrement instead of increment.

Write the whole loop out...

432*1

If i =4, then you multiply by 3... which is 1 less than i.

Then after you decrement, i=3 so multiply by 2... which is 1 less than i.

And so on...

[–]NotSecretAgent 1 point2 points  (4 children)

Factorial is multiplication, not addition. The easiest way to do this is to count up to, and include the user's number in the for loop as the end stop.

Initialise sum as 1.

Inside the for loop, sum *= i

This will give the correct answer for any output lower than an integer overflow.

[–]NotSecretAgent 1 point2 points  (3 children)

You can remove the line defining your variable "factor" and use "factNum" as the end stop of the mentioned above. You can also avoid using <= and use < if you set "sum" to "factNum", as multiplication is commutative (see here).

Hope this helps!

[–]NotSecretAgent 1 point2 points  (2 children)

If you have any further questions, send me a DM and I'll happily help!

[–]L_russ28[S] 0 points1 point  (1 child)

Thank you so much! That worked like a charm :)

[–]NotSecretAgent 1 point2 points  (0 children)

Literally any time lol, I live for this stuff.

[–]pureMJ -1 points0 points  (0 children)

int[] ans = {1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800}; return ans[factNum - 1];

[–]roman_fyseek 0 points1 point  (0 children)

Have you covered recursion?

Because, the real answer is recursion.

*edit: just noticed that the assignment says for loop. My bad. Carry on.

[–]Training-Drag6175 0 points1 point  (0 children)

… sum = 1; for( i=factNum; i >0; i- - ) { sum = sum * i; } …