# 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.

### Recommended Books

### Connect to us …

### Some recommendations…

### Recently added…

- Getting rid of Getters and Setters in your POJO January 17, 2015
- Using Google Guava Cache for local caching January 12, 2015
- Very useful Console Window for windows December 17, 2014
- Book Review: Murach’s Java Servlets And JSP 3rd Edition September 23, 2014
- Book Review: RESTful Web Services with Dropwizard by Alexandros Dallas September 8, 2014

### 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