Project Euler > Problem 43 > Sub-string divisibility (Java Solution)

Problem:

The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.

Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:

* d2d3d4=406 is divisible by 2
* d3d4d5=063 is divisible by 3
* d4d5d6=635 is divisible by 5
* d5d6d7=357 is divisible by 7
* d6d7d8=572 is divisible by 11
* d7d8d9=728 is divisible by 13
* d8d9d10=289 is divisible by 17

Find the sum of all 0 to 9 pandigital numbers with this property.


Solution:

16695334890


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

public interface EulerSolution{

public String run();

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


public final class p043 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p043().run());
 }
 
 
 private static int[] DIVISIBILITY_TESTS = {2, 3, 5, 7, 11, 13, 17};  // First 7 primes
 
 
 public String run() {
  long sum = 0;
  int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  outer:
  do {
   for (int i = 0; i < DIVISIBILITY_TESTS.length; i++) {
    if (toInteger(digits, i + 1, 3) % DIVISIBILITY_TESTS[i] != 0)
     continue outer;
   }
   sum += toInteger(digits, 0, digits.length);
  } while (Library.nextPermutation(digits));
  return Long.toString(sum);
 }
 
 
 private static long toInteger(int[] digits, int off, int len) {
  long result = 0;
  for (int i = off; i < off + len; i++)
   result = result * 10 + digits[i];
  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