Pages

Tuesday, September 8, 2009

Euler Problem 32 solution

Time (s): ~0.066
package margusmartseppcode.From_30_to_39;

import java.util.HashSet;
import java.util.Set;

public class Problem_32 {
 static final int nbrs = 9;

 static boolean isPandigital(String s) {
  return isPandigital(s, nbrs);
 }

 static boolean isPandigital(String s, int nr) {
  if (s.length() != nr)
   return false;

  Set<Character> set = new HashSet<<Character>();
  for (int i = 0; i < nr; i++)
   set.add(s.charAt(i));

  if (set.size() != nr)
   return false;
  if (set.contains('0'))
   return false;
  return true;
 }

 public static void main(String[] args) {
  Set<Integer> set = new HashSet<Integer>();
  int sum = 0;

  for (int i = 2, n = 1234; i < 100; i++, n = i > nbrs ? 123 : 1234)
   for (int j = n; j < (int) (10000 / i + 1); j++)
    if (isPandigital("" + i + j + (i * j)))
     set.add(i * j);

  for (Integer val : set)
   sum += val;

  System.out.println(sum);
 }
}

No comments:

Post a Comment