Java Program to Display Factors of a Number

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Factors of a Positive Integer

public class Main {

  public static void main(String[] args) {

    // positive number
    int number = 60;

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

    // loop runs from 1 to 60
    for (int i = 1; i <= number; ++i) {

      // if number is divided by i
      // i is the factor
      if (number % i == 0) {
        System.out.print(i + " ");
      }
    }
  }
}

Output

Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

In the above program, number whose factors are to be found is stored in the variable number (60).

The for loop is iterated until i <= number is false. In each iteration, whether number is exactly divisible by i is checked (condition for i to be the factor of number) and the value of i is incremented by 1.


Example 2: Factors of Negative Number

class Main {

  public static void main(String[] args) {

    // negative number
    int number = -60;
    System.out.print("Factors of " + number + " are: ");

    // run loop from -60 to 60
    for(int i = number; i <= Math.abs(number); ++i) {

      // skips the iteration for i = 0
      if(i == 0) {
        continue;
      }
      else {
        if (number % i == 0) {
          System.out.print(i + " ");
        }
      }
    }
  }
}

Output

Factors of -60 are: -60 -30 -20 -15 -12 -10 -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 10 12 15 20 30 60  

In the above example, we have computed all the factors of a negative number. Here, the for loop runs from -60 to 60.

And, when the value of i is 0, the iteration is skipped. Otherwise, there will be an exception.

Note: The Math.abs() method returns the absolute value of the number.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community