get Factors for an integer - Java java.lang

Java examples for java.lang:Math Number

Description

get Factors for an integer

Demo Code


//package com.java2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        int i = 20;
        System.out.println(getFactors(i));
    }//w w  w.j  a va2s  . c  om

    public static List<Integer> getFactors(int i) {
        List<Integer> factors = new ArrayList<>();
        factors.add(new Integer("1"));
        int sqr = (int) Math.sqrt(i) + 1;
        for (int x = 2; x < sqr; x++) {
            int factor = i / x;
            if (i % x == 0) {
                factors.add(new Integer(x));
                if (x != factor) {
                    factors.add(new Integer(factor));
                }
            }
        }
        return factors;
    }
}

Related Tutorials