-3

The factorial of a non-negative integer n, n!, is defined as the product of all positive integers less than or equal to n:

0! = 1

n! = 1×2×3×…×n

Find the bugs in the following code extract intended to compute the value of n!.

private int fact(int n){
    int nf = 1;
    for (int i = 1; i < n; ++i) {
        nf *= i; 
    }
    return nf; 
}

Once this is complete, I must Re-write this function to remove the “for” loop.

Any suggestions is greatly appreciated!

Danielson
  • 2,605
  • 2
  • 28
  • 51

1 Answers1

0

Is this a homework question? If so, you should mark it as such.

Anyways, the bug is here:

    for (int i = 1; i < n; ++i)
    {
        nf *= i; 
    }

In your for loop, you have it go up to n, which will compute (n-1)!. For example, putting in 4 will give you 1 * 2 * 3 which is 3!.

Fix it by looping it up to n, so i < n+1.

You can also use recursion:

int fact(int n){
    int nf;

    if(n==1)
       return 1;

    nf = fact(n-1) * n;
    return nf;
}
jstnchng
  • 2,161
  • 4
  • 18
  • 31