Search code examples
javalogicfactorial

How to add my logic as per my understanding factorial?


I am trying to calculate the factorial, like take an example 5!

5 * 4 * 3 * 2 * 1 = 120 right

20 * 3 * 2 * 1

60 * 2 * 1

120 * 1

120

How to apply this logic in code? I tried this:

int sum = 0;
int num = 5;
for (int i = 1; i <= num; i++)
{
  sum = num * (num - 1) 

I know this is wrong for for loop but if I use this I get the 5 * 4 = 20 for the first iteration

Or:

sum = 1;
sum = sum * (num - i)

It gives like this:

1 = 1 * 4 = 4;

4 = 4 * 3 = 12;

12 = 12 * 2 = 24

24 = 24 * 1 = 24


Solution

  • private int factorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("n < 0");
        }
    
        int sum = 1;
        for (int i = n; i > 1; i--) {
            sum *= i;
        }
        return sum;
    }