Pages

Sunday, September 13, 2009

Euler Problem 49 solution

Time (s): ~0.002
  1. package margusmartseppcode.From_40_to_49;  
  2.   
  3. import java.util.Arrays;  
  4.   
  5. public class Problem_49 {  
  6.   
  7.  // Call only if: (n>0&&(i%2==0||i%3==0||i%5==0||i%7==0))  
  8.  static boolean isPrimeS(final int n) {  
  9.   final int r = (int) Math.floor(Math.sqrt(n));  
  10.   for (int f = 5; f <= r; f += 6)  
  11.    if (n % f == 0 || n % (f + 2) == 0)  
  12.     return false;  
  13.   return true;  
  14.  }  
  15.   
  16.  static boolean isPerm(char[] a, char[] b) {  
  17.   if (a.length != b.length)  
  18.    return false;  
  19.   Arrays.sort(a);  
  20.   Arrays.sort(b);  
  21.   return Arrays.equals(a, b);  
  22.  }  
  23.   
  24.  static boolean arePerms(int... n) {  
  25.   if (n.length == 0)  
  26.    return true;  
  27.   for (int i = 1; i < n.length; i++)  
  28.    if (!isPerm(("" + n[i - 1]).toCharArray(), ("" + n[i])  
  29.      .toCharArray()))  
  30.     return false;  
  31.   return true;  
  32.  }  
  33.   
  34.  static boolean arePrimes(int... n) {  
  35.   for (int i : n)  
  36.    if (!isPrimeS(i))  
  37.     return false;  
  38.   
  39.   return true;  
  40.  }  
  41.   
  42.  public static void main(String[] args) {  
  43.   int a, b, c;  
  44.   a = b = c = 0;  
  45.   
  46.   for (a = 1489;; a += 2) {  
  47.    if (a % 3 == 0 || a % 5 == 0 || a % 7 == 0)  
  48.     continue;  
  49.      
  50.    b = a + 3330;  
  51.    c = a + 6660;  
  52.   
  53.    if (arePrimes(a, b, c))  
  54.     if (arePerms(a, b, c))  
  55.      break;  
  56.   }  
  57.   System.out.println("" + a + b + c);  
  58.  }  
  59. }  

No comments:

Post a Comment