How to Find Factors of a Number in Java

 

How to Find Factors of a Number in Java

A factor of a number N is an integer that divides N without leaving a remainder.

1️⃣ Basic Approach (Loop from 1 to N)

Time Complexity: O(N)O(N)


Simple but inefficient for large numbers


public class Factors {

    public static void main(String[] args) {

        int num = 12; // Change this to any number

        System.out.print("Factors of " + num + " are: ");

        

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

            if (num % i == 0) {

                System.out.print(i + " ");

            }

        }

    }

}


2️⃣ Optimized Approach (Loop Until √N)

Time Complexity: O(N)O(\sqrt{N})


More efficient

Finds factors in pairs



public class OptimizedFactors {

    public static void main(String[] args) {

        int num = 12; // Change this to any number

        System.out.print("Factors of " + num + " are: ");

        

        for (int i = 1; i * i <= num; i++) {

            if (num % i == 0) {

                System.out.print(i + " "); // First factor

                

                if (i != num / i) { // Second factor (avoid duplicate for perfect squares)

                    System.out.print((num / i) + " ");

                }

            }

        }

    }

}


Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence