My code:

package big;

import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        System.out.println (factorial (5));
    }

    public static int factorial (int n) {
        int f = 1;

        for (int i = 1; i <= n; i++) {
            f = f * i;
        }
        return f;
    }
}

How do I add two new variable nBig and fBig that convert x and n to BigInteger. Also how do i modify the return value for the pow method to BigInteger which means changing the type for the i variable too. Finally, how to rewrite those math operations using BigInteger operations.

Recommended Answers

All 7 Replies

I just don't understand how to work with BigIntegers.

Well BigInteger is just an object, so you instantiate it like any other object. Its constructor takes a String representation of a number. So a BigInteger with a value of 1 would be:

BigInteger ONE = new BigInteger( "1" );

So the code for your factorial method using BigInteger would look something like this:

public static BigInteger factorial( int n ) {
        BigInteger factorial = new BigInteger( "1" );
        BigInteger temp;
        for ( int i = 1; i <= n; i++ ) {            
            temp = new BigInteger( Integer.toString( i ) );
            factorial = factorial.multiply( temp );            
        }
        return factorial;
    }

The multiply() method takes a BigInteger object and multiplies it with the value of the object calling multiply(), and as i int the for loop is an int, we must change it to a BigInteger if we want to use its value in multiply().

If you look through the methods BigInteger has you should have no trouble implementing oter math operations using BigInteger . That is if I've helped you understand them a bit more!

Why did you change the integer to string?

The integer is changed to a String because the constructor for BigInteger takes a String representation of a number. BigInteger does not have a constructor that takes an int, and turns it into a BigInteger .

// This works, it turns i into a String, which is what one of the BigInteger constructors takes
int num = 1;
BigInteger test = new BigInteger( Integer.toString( num ) );

// This is WRONG, no BigInteger constructor can take an int, and turn it into a BigInteger
int num = 1;
BigInteger test = new BigInteger(  num  );

Oh, now I understand. Thanks for excellent explanation. :)

Now, how do I print a table until 30!?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.