Factorial Function with Java

Let’s say you needed a utility function to calculate the factorial of a number.

Below is an example preceded with its test function (in a TDD approach).

The unit test would look like this:

 @Test
 public final void factorialFunctionTest(){
     Assert.assertEquals(24, Factorial.factorialFunction(4));
 }
 
 @Test(expected = IllegalArgumentException.class)
 public final void factorialllegalArgumentExceptionTest(){
     Factorial.factorialFunction(-6);
 }
 

And the function like this:

 public static long factorialFunction(int n) {
     if (n < 1) {
         throw new IllegalArgumentException(
         "n cannot be negative");
     }
     long result = 1;
     for (int i = 1; i <= n; i++) {
         result *= i;
     }
     return result;
 }

 

Leave Comment

Your email address will not be published. Required fields are marked *