Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Factors of a Number in Java

Last Updated on August 6, 2024 by Abhishek Sharma

In mathematics and computer science, factors of a number are integers that can be multiplied together to produce the original number. Understanding and finding the factors of a number is a fundamental concept that often forms the basis of more complex algorithms and problem-solving techniques. In Java programming, determining the factors of a given number can be achieved through various approaches, each showcasing the power and versatility of the language.

Factors of a Number in Java with Various Methods

Finding every element of a given integer input is the aim. To achieve this, we’ll explore the range from 1 to the number itself using loops, checking each step for any factors. We will either add the number to the list of factors or only print the factors along the way if the integer is a factor of the number. We’ll now go over every method there is for finding a number’s factors in Java.:

Approach 1: Factors of a Number in Java using Loop

The for loop is the first method we use to determine a number’s factors. We perform a for loop from 1 to the number n, whose factors we must determine. The factors are then determined by looking for numbers that divide n exactly.

Code Implementation

class Factor {
    public static void main(String[] args) {

        // We store the number, of which we wish to obtain the factors in variable n
        int n = 40;

        // Now, using for loop and with the following logic, we shall determine the
        // factors of the integer stored in n
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                System.out.printf(" %d ", i);
            }
        }
    }
}

Output:

1  2  4  5  8  10  20  40 

Using a while or do-while loop, the same thing can be done. Only the syntax varies; the logic is the same in both cases.

Approach 2: Factors of a Number in Java using While Loop

In this method, we will use a while loop to find the factors of a number in Java. Everything is the same as the above approach, just a slight change in the loop, instead of for loop, we will use the while loop for implementing it.

Code Implementation

class PrepBytes {
    public static void main(String[] args) {

        // We store the number, of which we wish to obtain the factors in variable n
        int n = 40, i = 1;

        // Now, using the while loop and with the following logic, we shall determine the
        // factors of the integer stored in n
        while(i <= n) {
            if(n % i == 0) {
                System.out.printf(" %d ", i);
            }
            i++; // incrementing value
        }
    }
}

Output:

1  2  4  5  8  10  20  40 

Approach 3: Factors of a Number in Java using a Do-while Loop

The main logic is also the same for this logic, just a slight difference in running of the loop. Instead of a while loop, we will run a do-while loop to implement the logic.

Code Implementation

class PrepBytes {
    public static void main(String[] args) {

        // We store the number, of which 
        // we wish to obtain the factors, in variable n
        int n = 40, i = 1;

        // Now, using do while loop and with the following logic, 
        // we shall determine the factors of the integer stored in n
        do {
            if(n % i == 0) {
                System.out.printf(" %d ", i);
            }
            i++; // incrementing variable
        } while(i <= n);
    }
}

Output:

1  2  4  5  8  10  20  40

Finding all the factors of a number using the methods mentioned above is naive. Simply verifying each integer to see if it divides n and publishing the result, we iterate from 1 to n. The technique has an O(n) time complexity and an O(1) auxiliary space need.

Can the approach described above be improved? Yes, it is the answer. We will now go through a better method for determining a number’s factors.

Approach 4: Factors of a Number in Java with an Optimized Method

All of a number’s factors can be said to be present in pairs if they are carefully observed.

Example: The different pairings of divisors for n = 100 are (1,100), (2,50), (4,25), (5,20), and (10,10). Similar to this, the different pairs of divisors for n = 40 are (1,40), (2,20), (4,10), and (5,8).

The fact that this holds true for all other numbers allows us to come up with a more effective approach. The number’s square root is the single iteration that is necessary to produce all the pairs. It’s vital to remember that the number is only taken into account once for equal pairs (such as (10,10)).

Code Implementation

class PrepBytes {
    public static void main(String[] args) {

        // We store the number, of which we wish to obtain the factors, in variable n
        int n = 40;

        // Now, using for loop and with the following logic, we shall determine the
        // factors of the integer stored in n
        for (int i = 1; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                // If divisors are equal, print only one
                if (n/i == i)
                    System.out.print(" "+ i);
       
                else // Otherwise, print both
                    System.out.print(i+" " + n/i + " " );
            }
        }
    }
}

Output:

1 40 2 20 4 10 5 8 

Time Complexity: O(sqrt(n))

Auxiliary Space: O(1)

The answer provides all of the number’s factors, but as they are not sorted, there is still room for improvement. To our advantage, we may change the code such that it prints all factors in sorted order.

Since the pairings will be sorted, we shall print half of them first. The numbers that entirely divide the number will be produced as a result, and we can then print the quotient for each number to obtain the other half.

Code Implementation

class PrepBytes {
    public static void main(String[] args) {

        int n = 40; // given number

        int i; // declaring i in outer scope
        for (i = 1; i * i < n; i++) {
            if (n % i == 0)
                System.out.print(i + " "); // numbers  which left remainder 0
        }
// now decrementing i to calculate quotients
        if (i - (n / i) == 1) {
            i--;
        }
        for (; i >= 1; i--) // quotient of numbers which give remainder as 0
        {
            if (n % i == 0)
                System.out.print(n / i + " ");
        }
    }
}

Output

1 2 4 5 8 10 20 40 

Here also, time complexity remains the same O(sqrt(n)).

Factors of Negative Number

We can compute all of a negative number’s positive factors, duplicate them, then add a negative sign in front of the duplicates to discover its factors. To print all factors, we can also do this by traversing from -n to n. 0 must be disregarded because it will result in an error.

Code Implementation

public class PrepBytes {
  public static void main(String[] args) {

    // In this example, we will find factors of a negative number, so let's store a
    // negative integer in the variable n
    int n = -35;

    // Here, we need to iterate the values in a for loop running from +n to -n
    // excluding 0.
    for (int i = n; i <= Math.abs(n); ++i) {

      // For skipping 0, we will add the continue statement..
      if (i == 0) {
        continue;
      } else {
        if (n % i == 0) {
          System.out.printf(" %d ", i);
        }
      }
    }
  }
}

Output

-35  -7  -5  -1  1  5  7  35

Conclusion
Finding the factors of a number is a simple yet essential task in programming that helps build a strong foundation for more advanced topics. Java, with its rich set of libraries and straightforward syntax, provides an efficient way to determine factors and explore related mathematical concepts. By mastering this fundamental task, programmers can enhance their problem-solving skills and prepare for tackling more complex challenges in the field of computer science.

FAQ related to Factors of a Number in Java

FAQ related to Factors of a Number in Java are:

1. How can I find the factors of a number in Java?
You can find the factors of a number in Java by iterating from 1 to the number itself and checking if the number is divisible by each iterated value. If it is, the iterated value is a factor.

2. What is the time complexity of finding factors in Java?
The time complexity of finding factors of a number n is
O(n) in a straightforward approach, where you check each number from 1 to n. More optimized methods can reduce this complexity.

3. Can I optimize the process of finding factors?
Yes, you can optimize the process by iterating only up to the square root of the number. If i is a factor of n, then n/i is also a factor. This reduces the time complexity to O(n).

4. Is there a built-in Java method to find factors?
Java does not have a built-in method specifically for finding factors, but you can easily implement a method using basic control structures like loops and conditionals.

5. How do I handle large numbers when finding factors in Java?
For handling large numbers, ensure your loop and condition checks are efficient. Consider using data types like long to accommodate larger values, and optimize your algorithm to reduce unnecessary computations.

Leave a Reply

Your email address will not be published. Required fields are marked *