Skip to content
July 27, 2011 / oop123

Project Euler #80 – Java

You can see the problem here: Problem #80.

This is a simple question (especially because it’s only asking for the digits of 100 number). The only trouble I encountered is misinterpreting “100 decimal digits” with the digits after the decimal point instead of the mathematical definition (as all the digits including digits before decimal).

I used the Newton-Raphson method and Java’s BigDecimal to calculate the square roots. For those who don’t know how the Newton-Raphson method works: for any number n, take a guess for its square root, and you can get a new and better guess with guess = (n / guess + guess) / 2.

public static String sqrtTo100Digits(int num) {
	BigDecimal bnum = BigDecimal.valueOf(num);
	BigDecimal TWO = BigDecimal.valueOf(2);
	BigDecimal guess = BigDecimal.valueOf(num / 2);
	for (int i = 2; i <= 122; i += 10) {       //122 should ensure a precision of up to 100
		BigDecimal temp = bnum.divide(guess, i, BigDecimal.ROUND_HALF_UP);
		guess = guess.add(temp).divide(TWO);
	return guess.toString().substring(0, 101); //101 to account for decimal decimal point

The code of .main(String[] args) are then pretty straight forward.

int sum = 0;
for (int i = 2; i < 100; i++) {
	if (Math.sqrt(i) % 1 == 0) continue;
	String num = sqrtTo100Digits(i).toString();
	sum += num.charAt(0) - 48; //-48 converts a digit in char to its equivalent int
	for (int j = 2; j < num.length(); j++) {
		sum += num.charAt(j) - 48;

Runs in around 56 milliseconds on my computer. A simple question. CU


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: