# Finding Factorial of a Number in Java

# Finding Factorial of a Number in Java

Join the DZone community and get the full member experience.

Join For FreeHow do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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:

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Published at DZone with permission of Mohamed Sanaulla , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}