6/21/14

Factorization Tree.

108 number, as well as any other number, except for zero, in most sane situations, can be factored into divisor(s).

From divisors, a tree can be constructed.


Java source code (with unpolished output, other than that, seems fine):
----

package ft;

import java.util.LinkedList;
import java.util.List;

public class NumberFactored {
  private final int val;
  private final List<NumberFactored> divisors = new LinkedList<NumberFactored>();

  public NumberFactored(final int v) {
    this.val = v;
    this.evaluateAndSetDivisors();
  }

  private void evaluateAndSetDivisors() {
    if (val < 2) { return; }
    int threshold = (int) Math.floor(Math.sqrt(val));
    for (int i=2; i <= threshold; i++) {
      if ((val % i) == 0) {
        final NumberFactored divisor = new NumberFactored(i);
        divisors.add(divisor);
      }
    }
  }

  public String toString() {
    final StringBuilder result = new StringBuilder();
    for (final NumberFactored divisor : divisors) {
      result.append(val);
      result.append('/');
      result.append(divisor.val);
      result.append('=');
      result.append(val/divisor.val);
      result.append(';');
      final NumberFactored nf = new NumberFactored(val/divisor.val);
      result.append(nf.toString());
    }
    return result.toString();
  }

  public static void main(String[] args) {
    final NumberFactored n = new NumberFactored(108);
    System.out.println("factored:\n");
    System.out.println(n.toString());
  }
}

----

Sample output:


factored:

108/2=54;54/2=27;27/3=9;9/3=3;54/3=18;18/2=9;9/3=3;18/3=6;6/2=3;54/6=9;9/3=3;108/3=36;36/2=18;18/2=9;9/3=3;18/3=6;6/2=3;36/3=12;12/2=6;6/2=3;12/3=4;4/2=2;36/4=9;9/3=3;36/6=6;6/2=3;108/4=27;27/3=9;9/3=3;108/6=18;18/2=9;9/3=3;18/3=6;6/2=3;108/9=12;12/2=6;6/2=3;12/3=4;4/2=2;

No comments:

Post a Comment