Project Euler > Problem 141 > Investigating progressive numbers, n, which are also square. (Java Solution)

Problem:

A positive integer, n, is divided by d and the quotient and remainder are q and r respectively. In addition d, q, and r are consecutive positive integer terms in a geometric sequence, but not necessarily in that order.

For example, 58 divided by 6 has quotient 9 and remainder 4. It can also be seen that 4, 6, 9 are consecutive terms in a geometric sequence (common ratio 3/2).
We will call such numbers, n, progressive.

Some progressive numbers, such as 9 and 10404 = 1022, happen to also be perfect squares.
The sum of all progressive perfect squares below one hundred thousand is 124657.

Find the sum of all progressive perfect squares below one trillion (1012).


Solution:

7652413

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

public interface EulerSolution{

public String run();

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


public final class p041 implements EulerSolution {

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


public String run() {
for (int n = 9; n >= 1; n--) {
int[] digits = new int[n];
for (int i = 0; i < digits.length; i++)
digits[i] = i + 1;

int result = -1;
do {
if (Library.isPrime(toInteger(digits)))
result = toInteger(digits);
} while (Library.nextPermutation(digits));
if (result != -1)
return Integer.toString(result);
}
throw new RuntimeException("Not found");
}


private static int toInteger(int[] digits) {
int result = 0;
for (int x : digits)
result = result * 10 + x;
return result;
}

}


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