Quote:
quote:Originally posted by new_bie
i've been working on a problem in school and i cant seem to find a solution
product = 1;
for (int x = 1000000; x >=1; x --)
{
product = product * x;
}
how can i declare a variable product capable of holding a 1000000! value? int, float, double, doesn't seem to solve the problem.
newbie
|
Indeed.
You need the BigInteger class newbie!
You can read about it in the SDK API docs in the package called math
Not java.lang.Math but java.math.BigInteger
So for a factorial the method declaration could be:
public static java.math.BigInteger factorial(int number)
{
java.math.BigInteger fact = java.math.BigInteger.ONE;
if(number < 0)
return null;
for(int i=1; i<=number; i++)
{
java.math.BigInteger newFactor = new java.math.BigInteger(
Integer.toString(i));
fact = fact.multiply(newFactor);
}
return fact;
}
There is a BigInteger.toString() that you can use to
System.out.println() your BigInteger.
This should work I guess,
of course you can import java.math in your class
then you can skip the java.math prefix of BigInteger
OK?
Franz