Java examples for java.lang:Math Value
Return the factorial value of the input.
//package com.java2s; import java.math.BigInteger; public class Main { /** Return the factorial value of the input. * Note: Numbers can quickly overwhelm the MAX_LONG and cause wrap-around. * Note: Currently, negative numbers are not supported and will throw an IllegalArgumentException. */ public static BigInteger factorial(long num) { if (num < 0) { throw new IllegalArgumentException("Input must be non-negative"); }/*from www . j a v a 2 s .co m*/ if (num == 0) { return BigInteger.ONE; } // Source: http://mathforum.org/dr.math/faq/faq.0factorial.html BigInteger product = BigInteger.ONE; for (BigInteger i = new BigInteger("" + num); i .compareTo(BigInteger.ZERO) > 0; i = i .subtract(BigInteger.ONE)) { product = product.multiply(i); } System.out.println("factorial(" + num + ")=" + product); return product; } }