# Finding factorial of a number in Java

*By Mohamed Sanaulla On January 28, 2013 · Leave a Comment*

If you have tried to find a factorial using int as the data type, its most likely that you will soon get wrong outputs because the factorial value overflows the size of the int. One approach to over come is to use java.math.BigInteger to perform the factorial calculations and write a iterative/recursive method to find the factorial. Another approach would be to use com.google.common.math.BigIntegerMath provided by Google Guava API. I will show how to use both of these approaches in the post below:

### Iterative based factorial calculation using BigInteger

import java.math.BigInteger; import java.util.Scanner; public class FactorialTest { public static void main(String[] args) { int number; Scanner reader = new Scanner(System.in); while(true){ System.out.println("Enter the number for finding factorial"); // Read the number for finding factorial number = reader.nextInt(); if (number == -1){ break; } System.out.println("The factorial is: "+factorial(number)); } } /** * Obtaining the factorial of a given number */ public static BigInteger factorial(int number){ //Note that we have used BigInteger to store the factorial value. BigInteger factValue = BigInteger.ONE; for ( int i = 2; i <= number; i++){ factValue = factValue.multiply(BigInteger.valueOf(i)); } return factValue; } }

The output for the above code:

### Google Guava API to find factorial:

I have used Eclipse to execute these samples and for using Google Guava you need to add the Google Guava library jar into the classpath of your project as shown below:

and after adding the jar you would see it being visible in the referenced libraries:

com.google.common.math.BigIntegerMath has a method factorial() which accepts a int value and returns factorial which would be of BigInteger type:

import java.util.Scanner; import com.google.common.math.BigIntegerMath; public class FactorialGuavaTest { public static void main(String[] args) { int number; Scanner reader = new Scanner(System.in); while(true){ System.out.println("Enter the number for finding factorial"); number = reader.nextInt(); System.out.println("The factorial is: "+BigIntegerMath.factorial(number)); } } }

The output for the above code is:

No related posts.

### Connect to us …

### Some recommendations…

### Recently added…

- Book Review: Java Performance by Charlie Hunt and Binu John August 20, 2014
- Getting started with Mocking in Java using Mockito February 23, 2014
- Another sample for using JAXB November 24, 2013
- Book Review: Peopleware October 25, 2013
- JSON Processing support in JavaEE 7 and JSR-353 October 18, 2013

### Archives

### Disclaimer

Some of the links contained within this site have my referral id, which provides me with a small commission for each sale. Thank you for your support.

## Recent Comments