Wrox Programmer Forums
|
BOOK: Beginning Java 2
This is the forum to discuss the Wrox book Beginning Java 2, SDK 1.4 Edition by Ivor Horton; ISBN: 9780764543654
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Beginning Java 2 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old October 20th, 2004, 08:55 PM
Registered User
 
Join Date: Oct 2004
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via Yahoo to new_bie
Default 1000000 Factorial

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

newbie
 
Old October 29th, 2004, 12:01 PM
Authorized User
 
Join Date: Sep 2003
Posts: 98
Thanks: 0
Thanked 0 Times in 0 Posts
Default

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





Similar Threads
Thread Thread Starter Forum Replies Last Post
Factorial of numbers 1 to 5 sivakak Javascript 1 May 24th, 2007 09:31 AM
Factorial of numbers 1 to 5 sivakak BOOK: Beginning PHP4/PHP 5 ISBN: 978-0-7645-4364-7; v5 ISBN: 978-0-7645-5783-5 0 May 24th, 2007 08:42 AM
doing a factorial using a for loop mattrd Javascript How-To 1 July 28th, 2003 05:11 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.