Project Euler > Problem 135 > Same differences (Java Solution)

Problem:

Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 [−] y2 [−] z2 = n, has exactly two solutions is n = 27:

342 [−] 272 [−] 202 = 122 [−] 92 [−] 62 = 27

It turns out that n = 1155 is the least value which has exactly ten solutions.

How many values of n less than one million have exactly ten distinct solutions?


Solution:

55

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

public interface EulerSolution{

public String run();

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


public final class p035 implements EulerSolution {

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


private static final int LIMIT = Library.pow(10, 6);

private boolean[] isPrime = Library.listPrimality(LIMIT - 1);


public String run() {
int count = 0;
for (int i = 0; i < isPrime.length; i++) {
if (isCircularPrime(i))
count++;
}
return Integer.toString(count);
}


private boolean isCircularPrime(int n) {
String s = Integer.toString(n);
for (int i = 0; i < s.length(); i++) {
if (!isPrime[Integer.parseInt(s.substring(i) + s.substring(0, i))])
return false;
}
return true;
}

}

No comments:

Post a Comment