Square root   Leave a comment


Integer square root should work only if the given number has an integer square root

import java.math.BigInteger;

public class SquareRoot {
	public static BigInteger squareRoot(BigInteger num) {
		BigInteger high = num;
		BigInteger low = BigInteger.ONE;
		BigInteger two = BigInteger.valueOf(2);
		BigInteger res;
		BigInteger mid;
		do {
			mid = high.add(low).divide(two);
			if ((res = mid.multiply(mid)).compareTo(num) < 0)
				low = mid;
			else
				high = mid;
		} while (res.compareTo(num) != 0);
		return mid;
	}

	public static double squareRoot(double d) {
		double high = Math.ceil(d);
		double low = 0;
		double mid = 0;
		do {
			mid = (high + low) / 2;
			if (mid * mid > d)
				high = mid;
			else
				low = mid;

		} while (Math.abs(mid * mid - d) > 1e-15);
		return mid;
	}
}
Advertisements

Posted August 21, 2011 by epicrado in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: