Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active December 19, 2015 08:49
Show Gist options
  • Save sshark/5928921 to your computer and use it in GitHub Desktop.
Save sshark/5928921 to your computer and use it in GitHub Desktop.
Factorial using BigDecimal
package org.thlim;
import java.math.BigDecimal;
/**
*
*
* @author Lim, Teck Hooi
*
*/
public class FactorialWithBigDecimal
{
public static void main(String[] args)
{
BigDecimal initial = BigDecimal.valueOf(Integer.parseInt(args[0]));
System.out.println(initial + "! = " + fac(initial, initial));
}
static BigDecimal fac(BigDecimal n, BigDecimal acc) {
if (n.equals(BigDecimal.ONE)) {
return acc;
}
BigDecimal lessOne = n.subtract(BigDecimal.ONE);
return fac(lessOne, acc.multiply(lessOne));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment