Project Euler > Problem 32 > Pandigital products (Java Solution)

Problem:

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 [×] 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.


Solution:

45228


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

public interface EulerSolution{

public String run();

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

import java.util.Arrays;


public final class p032 implements EulerSolution {
 
 public static void main(String[] args) {
  System.out.println(new p032().run());
 }
 
 
 public String run() {
  // A candidate product has at most 4 digits. This is because if it has 5 digits,
  // then the two multiplicands must have at least 5 digits put together.
  int sum = 0;
  for (int i = 1; i < 10000; i++) {
   if (hasPandigitalProduct(i))
    sum += i;
  }
  return Integer.toString(sum);
 }
 
 
 private static boolean hasPandigitalProduct(int n) {
  // Find and examine all factors of n
  for (int i = 1; i <= n; i++) {
   if (n % i == 0 && isPandigital("" + n + i + n/i))
    return true;
  }
  return false;
 }
 
 
 private static boolean isPandigital(String s) {
  if (s.length() != 9)
   return false;
  char[] temp = s.toCharArray();
  Arrays.sort(temp);
  return new String(temp).equals("123456789");
 }
 
}


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