package com.primeFactorizer;

/**
 * This class factorizes a prime number.
 * @author fpereira
 *
 */
public final class PrimeFactorizer {
  /**
   * The largest number of factors any input number can have.
   */
  public static final int MAX_NUM_FACTORS = 64;

  /**
   * The number of prime factors in the number.
   */
  private static int factorIndex;

  /**
   * The array with factors.
   */
  private static int[] factorRegister;

  /**
   * Private constructor, to avoid instantiation.
   */
  private PrimeFactorizer() { }

  /**
   * Factors an integer number.
   * @param multiple the number to be factored.
   * @return an array with all the prime factors in the number.
   */
  public static int[] factor(final int multiple) {
    initialize();
    findPrimeFactors(multiple);
    return copyToResult();
  }

  /**
   * Set the variables to an initial state.
   */
  private static void initialize() {
    factorIndex = 0;
    factorRegister = new int[MAX_NUM_FACTORS];
  }

  /**
   * Find all the prime factors of the number.
   * @param multiple the number that will be factored.
   */
  private static void findPrimeFactors(final int multiple) {
    int aux = multiple;
    for (int factor = 2; aux != 1; factor++) {
      for (; (aux % factor) == 0; aux /= factor) {
        factorRegister[factorIndex++] = factor;
      }
    }
  }

  /**
   * We are finding the prime factors in a bigger array than it may be
   * necessary. So we must trim the array.
   * @return The trimmed array with all the prime factors of the number.
   */
  private static int[] copyToResult() {
    int[] factors = new int[factorIndex];
    for (int i = 0; i < factorIndex; i++) {
      factors[i] = factorRegister[i];
    }
    return factors;
  }

}
