Java examples for java.lang:Math Number
Returns the factorial of an integer.
/*/*from w w w. j av a2s . com*/ * ------------------------------------------------------------------------= * Copyright (C) 1997 - 1998 by Visual Numerics, Inc. All rights reserved. * * Permission to use, copy, modify, and distribute this software is freely * granted by Visual Numerics, Inc., provided that the copyright notice * above and the following warranty disclaimer are preserved in human * readable form. * * Because this software is licenses free of charge, it is provided * "AS IS", with NO WARRANTY. TO THE EXTENT PERMITTED BY LAW, VNI * DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO ITS PERFORMANCE, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * VNI WILL NOT BE LIABLE FOR ANY DAMAGES WHATSOEVER ARISING OUT OF THE USE * OF OR INABILITY TO USE THIS SOFTWARE, INCLUDING BUT NOT LIMITED TO DIRECT, * INDIRECT, SPECIAL, CONSEQUENTIAL, PUNITIVE, AND EXEMPLARY DAMAGES, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * ------------------------------------------------------------------------= */ //package com.java2s; public class Main { /** * Returns the factorial of an integer. * * @param n * An integer value. * @return The factorial of n, n!. If x is negative, the result is NaN. */ static public double fact(int n) { double ans = 1; if (Double.isNaN(n) || n < 0) { ans = Double.NaN; } else if (n > 170) { // The 171! is too large to fit in a double. ans = Double.POSITIVE_INFINITY; } else { for (int k = 2; k <= n; k++) ans *= k; } return ans; } }