Is there a method that calculates a factorial in Java?

Viewed 364952

I didn't find it, yet. Did I miss something? I know a factorial method is a common example program for beginners. But wouldn't it be useful to have a standard implementation for this one to reuse? I could use such a method with standard types (Eg. int, long...) and with BigInteger / BigDecimal, too.

30 Answers

I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.

Bare naked factorials are rarely needed in practice. Most often you will need one of the following:

1) divide one factorial by another, or

2) approximated floating-point answer.

In both cases, you'd be better with simple custom solutions.

In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)

In case (2), google for "Stirling's approximation".

Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.

The only business use for a factorial that I can think of is the Erlang B and Erlang C formulas, and not everyone works in a call center or for the phone company. A feature's usefulness for business seems to often dictate what shows up in a language - look at all the data handling, XML, and web functions in the major languages.

It is easy to keep a factorial snippet or library function for something like this around.

A very simple method to calculate factorials:

private double FACT(double n) {
    double num = n;
    double total = 1;
    if(num != 0 | num != 1){
        total = num;
    }else if(num == 1 | num == 0){
        total = 1;
    }
    double num2;
    while(num > 1){
        num2 = num - 1;
        total = total * num2;
        num = num - 1;
    }
    return total;
}

I have used double because they can hold massive numbers, but you can use any other type like int, long, float, etc.

P.S. This might not be the best solution but I am new to coding and it took me ages to find a simple code that could calculate factorials so I had to write the method myself but I am putting this on here so it helps other people like me.

You can use recursion version as well.

static int myFactorial(int i) {
    if(i == 1)
        return;
    else
        System.out.prinln(i * (myFactorial(--i)));
}

Recursion is usually less efficient because of having to push and pop recursions, so iteration is quicker. On the other hand, recursive versions use fewer or no local variables which is advantage.

I got this from EDX use it! its called recursion

   public static int factorial(int n) {
    if (n == 1) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}

using recursion is the simplest method. if we want to find the factorial of N, we have to consider the two cases where N = 1 and N>1 since in factorial we keep multiplying N,N-1, N-2,,,,, until 1. if we go to N= 0 we will get 0 for the answer. in order to stop the factorial reaching zero, the following recursive method is used. Inside the factorial function,while N>1, the return value is multiplied with another initiation of the factorial function. this will keep the code recursively calling the factorial() until it reaches the N= 1. for the N=1 case, it returns N(=1) itself and all the previously built up result of multiplied return N s gets multiplied with N=1. Thus gives the factorial result.

static int factorial(int N) {
    if(N > 1) { 
    return n * factorial(N - 1);
    }
    // Base Case N = 1
    else { 
    return N;
    }

public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    long fact = 1;
    for (int i = 1; i <= number; ++i) {
        fact *= i;
    }
    return fact;
}

using recursion.


public static long factorial(int number) {
    if (number < 0) {
        throw new ArithmeticException(number + " is negative");
    }
    return number == 0 || number == 1 ? 1 : number * factorial(number - 1);
}

source

Using Java 9+, you can use this solution. This uses BigInteger, ideal for holding large numbers.

...    
import java.math.BigInteger;
import java.util.stream.Stream;
...

String getFactorial(int n) {
    return Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE)).parallel() 
            .limit(n).reduce(BigInteger.ONE, BigInteger::multiply).toString();
}

USING DYNAMIC PROGRAMMING IS EFFICIENT

if you want to use it to calculate again and again (like caching)

Java code:

int fact[]=new int[n+1]; //n is the required number you want to find factorial for.
int factorial(int num)
 {
    if(num==0){
     fact[num]=1;
     return fact[num];
       }
     else
       fact[num]=(num)*factorial(num-1);

     return fact[num];
 }
Related