Project Euler > Problem 134 > Prime pair connection (Java Solution)

Problem:

Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p1 whilst also being divisible by p2.

In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive primes, p2 [>] p1, there exist values of n for which the last digits are formed by p1 and n is divisible by p2. Let S be the smallest of these values of n.

Find [∑] S for every pair of consecutive primes with 5 [≤] p1 [≤] 1000000.


Solution:

40730

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

public interface EulerSolution{

public String run();

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


public final class p034 implements EulerSolution {

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


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


// Hard-coded values for factorial(0), factorial(1), ..., factorial(9)
private static int[] FACTORIAL = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};

private static int factorialDigitSum(int x) {
int sum = 0;
while (x != 0) {
sum += FACTORIAL[x % 10];
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