Pages

Showing posts with label factors. Show all posts
Showing posts with label factors. Show all posts

Sunday, September 13, 2009

Euler Problem 47 solution

Time (s): ~0.067
package margusmartseppcode.From_40_to_49;

public class Problem_47 {
 static int unique_factors(int num, int[] primes, int[] factors) {
  int max = (int) Math.sqrt(num);

  for (int i = 0; primes[i] <= max; i++)
   if ((num % primes[i]) == 0) {
    do {
     num /= primes[i];
    } while ((num % primes[i]) == 0);

    return num == 1 ? 1 : factors[num] + 1;
   }

  return 0;
 }

 // creates primes and factors on fly
 public static void main(String[] args) {
  int n = 0, ps = 1, max = 200000;
  int primes[] = new int[max], factors[] = new int[max];

  for (n = 3, primes[0] = 2; n < max; n++)
   if ((factors[n] = unique_factors(n, primes, factors)) == 0) {
    factors[n] = 1;
    primes[ps++] = n;
   } else if ((factors[n] == 4) && (factors[n - 1] == 4)
     && (factors[n - 2] == 4) && (factors[n - 3] == 4))
    break;

  System.out.println(n - 3);
 }
}

Tuesday, September 8, 2009

Euler Problem 23 solution

Time (s): ~0.231
package margusmartseppcode.From_20_to_29;

public class Problem_23 {
 public static boolean IsAbundant(int num) {
  int factorSum = 1;
  double temp = Math.sqrt(num);

  if (temp % 1 == 0)
   factorSum -= temp;
  for (int i = 2; i <= temp; i++)
   if (num % i == 0)
    factorSum += i + num / i;

  if (factorSum > num)
   return true;

  return false;
 }

 public static void main(String[] args) {
  final int size = 28123;
  int[] d = new int[8192];
  int[] not = new int[size];
  int c = 0, c2 = 0, sum = 0;

  for (int i = 10; i <= size; i++)
   if (IsAbundant(i))
    d[c++] = i;

  for (int i = 0; i < c; i++)
   for (int j = i; j < c; j++)
    if ((c2 = d[i] + d[j]) < size)
     not[c2] = 1;

  for (int i = 1; i < size; i++)
   if (not[i] != 1)
    sum += i;

  System.out.println(sum);
 }
}