Project Euler > Problem 145 > How many reversible numbers are there below one-billion? (Java Solution)

Problem:

Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n).

There are 120 reversible numbers below one-thousand.

How many reversible numbers are there below one-billion (109)?


Solution:

1533776805

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

public interface EulerSolution{

public String run();

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


public final class p045 implements EulerSolution {

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


public String run() {
int i = 286;
int j = 166;
int k = 144;
while (true) {
long triangle = (long)i * (i + 1) / 2;
long pentagon = (long)j * (j * 3 - 1) / 2;
long hexagon = (long)k * (k * 2 - 1);
long min = Math.min(Math.min(triangle, pentagon), hexagon);
if (min == triangle && min == pentagon && min == hexagon)
return Long.toString(min);
if (min == triangle) i++;
if (min == pentagon) j++;
if (min == hexagon ) k++;
}
}

}

No comments:

Post a Comment