package margusmartseppcode.From_40_to_49; import java.util.HashSet; import java.util.Set; public class Problem_41 { static final int nbrs = 7; 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; if (set.contains('8')) return false; if (set.contains('9')) return false; return true; } // Call only if: (n>0&&(i%2==0||i%3==0||i%5==0||i%7==0)) static boolean isPrimeS(final int n) { final int r = (int) Math.floor(Math.sqrt(n)); for (int f = 5; f <= r; f += 6) if (n % f == 0 || n % (f + 2) == 0) return false; return true; } public static void main(String[] args) { int i; for (i = 7654321; i >= 1234567; i -= 2) { if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0) continue; if (!isPrimeS(i)) continue; if (isPandigital("" + i)) break; } System.out.println(i); } }
Wednesday, September 9, 2009
Euler Problem 41 solution
Time (s): ~0.009
Labels:
Euler Problem 40-49,
HashSet,
pandigital,
prime numbers
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment