I have this code:

public static int pow (int x, int n) {
if (n==0) return 1;

int t = pow (x, n/2);

if (n%2 == 0) {
return t*t;
} else {
return t*t*x;
}
}

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

The problem with this method is that it will only work if the result is smaller than 2 billion. I need rewrite it so that the result is a BigInteger. Please Help :(

Recommended Answers

All 2 Replies

Try this code snippet, it uses the constructors and methods of the BigInteger class,

public static BigInteger pow (String strX, String strN) {
		BigInteger x = new BigInteger(strX);
		BigInteger n = new BigInteger(strN);
		BigInteger BigZero = new BigInteger("0");
		BigInteger BigTwo = new BigInteger("2");
		if (n.equals(BigZero)) return new BigInteger("1");
	 
		BigInteger t = pow (x.toString(), (n.divide(BigTwo)).toString());
	 
		if ((n.mod(BigTwo)).equals(BigZero)) {
			return t.multiply(t);
		} else {
			return (t.multiply(t)).multiply(x);
		}
	}
	 
	public static void main(String[] args) {
			System.out.println (pow ("5", "2"));
	}

By the way there is a pow() function in the BigInteger class as well. See if that is satisfying your requirement instead of reinventing the wheel

Thanks for your Help!!!!!!

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.