How to find all divisors of a number in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EfficientDivisors {

    /**
     * Function: findDivisors
     * Purpose: Efficiently find all divisors of a number using the √n method.
     *
     * Explanation:
     *   - We loop only up to Math.sqrt(number), which greatly reduces iterations.
     *   - If i divides number, then both i and number / i are divisors.
     *   - If i == number / i (perfect square), we add it only once.
     *   - Finally, we sort the list so the divisors appear in ascending order.
     */
    public static List<Integer> findDivisors(int number) {
        List<Integer> divisors = new ArrayList<>();

        int limit = (int) Math.sqrt(number);

        for (int i = 1; i <= limit; i++) {

            // Check if i divides number
            if (number % i == 0) {
                divisors.add(i); // Add the smaller divisor

                // Add the paired divisor only if it's different
                if (i != number / i) {
                    divisors.add(number / i);
                }
            }
        }

        // Sort divisors in ascending order
        Collections.sort(divisors);

        return divisors;
    }

    public static void main(String[] args) {

        int num = 24;  

        // Call the efficient divisor function
        List<Integer> result = findDivisors(num);

        // Print the result
        System.out.println("Divisors of " + num + ": " + result);
    }
}


/*
run:

Divisors of 24: [1, 2, 3, 4, 6, 8, 12, 24]

*/

 



answered Jun 30, 2020 by avibootz
edited Jul 1 by avibootz
...