Project Euler > Problem 80 > Square root digital expansion (Java Solution)

Problem:

It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.

The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.

For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.


Solution:

443839

Code:
The solution may include methods that will be found here: Library.java .

public interface EulerSolution{

public String run();

}
/* 
* Solution to Project Euler problem 30
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/


public final class p030 implements EulerSolution {

public static void main(String[] args) {
System.out.println(new p030().run());
}


public String run() {
// As stated in the problem, 1 = 1^5 is excluded.
// If a number has at least n >= 7 digits, then even if every digit is 9,
// n * 9^5 is still less than the number (which is at least 10^n).
int sum = 0;
for (int i = 2; i < 1000000; i++) {
if (i == fifthPowerDigitSum(i))
sum += i;
}
return Integer.toString(sum);
}


private static int fifthPowerDigitSum(int x) {
int sum = 0;
while (x != 0) {
int y = x % 10;
sum += y * y * y * y * y;
x /= 10;
}
return sum;
}

}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact