Reports some non-trivial factor of a composite number. - Java java.lang

Java examples for java.lang:Math Number

Description

Reports some non-trivial factor of a composite number.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(aNonTrivialFactorV1(n));
    }/*from w ww .  java  2s  .co  m*/

    /**
     * Reports some non-trivial factor of a composite number.
     * 
     * @param n
     *            the given number
     * @return a non-trivial factor of the given number
     * @requires <pre>
     * {@code n > 2 and [n is not a prime number]}
     * </pre>
     * @ensures <pre>
     * {@code 1 < aNonTrivialFactorV1 < n and n mod aNonTrivialFactorV1 = 0}
     * </pre>
     */
    public static int aNonTrivialFactorV1(int n) {
        assert n > 2 : "Violation of: n > 2";
        int factor = 3;
        boolean found = false;
        while (!found) {
            if (n % factor == 0) {
                found = true;
            } else {
                factor = factor + 2;
            }
        }
        return factor;
    }
}

Related Tutorials