Gets a list of divisors of a number - Java java.lang

Java examples for java.lang:Math Number

Description

Gets a list of divisors of a number

Demo Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/*from   ww  w.j  a  v a  2s. co  m*/
     * Gets a list of divisors of a number
     *
     * @param num The number to get divisors for
     * @return The list of divisors
     */
    public static List<Long> getDivisors(long num) {
        List<Long> nums = new ArrayList<Long>();
        for (long i = 1; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                if (i == Math.sqrt(num) || i == 1) {
                    nums.add(i);
                } else {
                    nums.add(i);
                    nums.add(num / i);
                }
            }
        }
        return nums;
    }
}

Related Tutorials