Be aware that with factorials the calculated value grows large extremely quickly, which is why this
method returns a long. You could even make a case for returning a BigInteger instance here.
BigInteger objects have no upper bound; they allow for numerical integer values of any size.
// An iterative implementation of a factorial
public static long factorial (int n)
{
if (n < 1)
throw new IllegalArgumentExcpetion("n must be greater than zero");
long res =1;
for (int i =1; i < =n ; i++)
res*=i;
return res;
}
No comments:
Post a Comment