Java Program to Find All Factors of a Number
A factor of a positive integer is a number that divides it exactly, leaving a remainder of 0. For example, the factors of 8 are 1, 2, 4, and 8.
In Java, the remainder can be checked with the modulus operator %. If num % i == 0, then i is a factor of num.
We shall use two approaches. The first checks every integer from 1 through the given number. The second uses factor pairs and checks possible divisors only up to the square root of the number, which requires fewer iterations for larger values.
Find All Factors of a Number in Java Using a for Loop
In the following Java program, we shall find all the factors of a given number. We shall take the number in a variable num.
Write a for loop, that checks each number from 1 to that number, whether this number is a factor.
For every value of i, evaluate num % i. A remainder of 0 means that i divides num exactly and is therefore a factor.
Example.java
/**
* Java Program - Print Factors of Number
*/
public class Example {
public static void main(String[] args) {
//number
int num = 8;
//find all factors
for(int i = 1; i <= num; ++i) {
//check if i is a factor of num
if(num % i == 0) {
System.out.print(i+" ");
}
}
}
}
Run the above Java Program. It prints all the factors of number 8.
Output
1 2 4 8
The values 1, 2, 4, and 8 are printed because each produces a remainder of zero when 8 is divided by it.
How the Java for Loop Tests Each Possible Factor of 8
The following snippet provides values of different variables in the program, during each iteration of for loop in the above Java program.
Iteration 1
num : 8
i : 1
condition (8 % 1 == 0) is true
1 is a factor.
Iteration 2
num : 8
i : 2
condition (8 % 2 == 0) is true
2 is a factor.
Iteration 3
num : 8
i : 3
condition (8 % 3 == 0) is false
3 is not a factor.
Iteration 4
num : 8
i : 4
condition (8 % 4 == 0) is true
4 is a factor.
Iteration 5
num : 8
i : 5
condition (8 % 5 == 0) is false
5 is not a factor.
Iteration 6
num : 8
i : 6
condition (8 % 6 == 0) is false
6 is not a factor.
Iteration 7
num : 8
i : 7
condition (8 % 7 == 0) is false
7 is not a factor.
Iteration 8
num : 8
i : 8
condition (8 % 8 == 0) is true
8 is a factor.
This approach is straightforward: for a positive number n, it performs n divisibility checks. Its time complexity is O(n).
Find Factors Efficiently in Java Using Factor Pairs
Factors occur in pairs. If i divides num, then num / i is also a factor. For example, the factor pairs of 80 include 1 × 80, 2 × 40, 4 × 20, 5 × 16, and 8 × 10.
Because one member of each factor pair must be less than or equal to the square root of the number, it is sufficient to test divisors only while i <= num/i. The condition avoids calculating a square root and also avoids the overflow risk that could occur with an expression such as i * i <= num for sufficiently large integer values.
Example.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Java Program - Print Factors of Number
*/
public class Example {
public static void main(String[] args) {
//number
int num = 80;
//store factors in this list
List<Integer> factors = new ArrayList<Integer>();
for(int i = 1; i <= num/i; ++i) {
if(num % i == 0) {
//if i is a factor, num/i is also a factor
factors.add(i);
factors.add(num/i);
}
}
//sort the factors
Collections.sort(factors);
//print the factors
factors.forEach(factor -> System.out.print(factor+" "));
}
}
Run the above program. You shall get the following output printed to the console.
Output
1 2 4 5 8 10 16 20 40 80
For num = 80, the loop tests i from 1 through 8. Once a divisor is found, both i and num / i are added. The collected factors are then sorted before they are printed.
This factor-pair approach requires only about the square root of n divisibility checks, giving it a time complexity of O(√n) for finding the factor pairs. The sorting step in this particular implementation adds additional work for ordering the collected factors.
Avoid Duplicate Factors for Perfect Squares in Java
The factor-pair program above works as shown for 80, but a perfect square needs one additional check. For a number such as 36, when i reaches 6, both i and num / i are 6. Adding both values would store the same factor twice.
Check whether the two members of the factor pair are different before adding the second value.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Example {
public static void main(String[] args) {
int num = 36;
List<Integer> factors = new ArrayList<>();
for (int i = 1; i <= num / i; i++) {
if (num % i == 0) {
factors.add(i);
if (i != num / i) {
factors.add(num / i);
}
}
}
Collections.sort(factors);
System.out.println(factors);
}
}
For 36, the factor 6 is added only once.
[1, 2, 3, 4, 6, 9, 12, 18, 36]
Java Method to Return All Positive Factors of a Number
If factor calculation is needed in more than one place, it can be placed in a separate method. The following method accepts a positive integer and returns its positive factors in ascending order.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Example {
static List<Integer> findFactors(int num) {
if (num <= 0) {
throw new IllegalArgumentException("Number must be positive");
}
List<Integer> factors = new ArrayList<>();
for (int i = 1; i <= num / i; i++) {
if (num % i == 0) {
factors.add(i);
if (i != num / i) {
factors.add(num / i);
}
}
}
Collections.sort(factors);
return factors;
}
public static void main(String[] args) {
System.out.println(findFactors(24));
}
}
[1, 2, 3, 4, 6, 8, 12, 24]
Factor Cases to Handle in a Java Program
Programs that find factors should define how they handle a few important input cases:
- Number 1: the only positive factor of
1is1. - Prime number: a positive prime number has exactly two positive factors,
1and the number itself. For example, the positive factors of13are1and13. - Perfect square: the square-root factor must be included only once. For
36,6 × 6represents a single factor value6. - Zero: a finite list of all integer factors cannot be produced for
0, because every non-zero integer divides zero exactly. - Negative number: decide whether the program should return only the positive factors of its absolute value or both positive and negative divisors. The examples in this tutorial are defined for positive integers.
Why Checking Factors Only Up to the Square Root Works
Suppose n = a × b. If both a and b were greater than √n, their product would be greater than n. Therefore, every factor pair has at least one member that is less than or equal to √n.
For 80, once divisors through 8 have been checked, their paired factors provide all values greater than the square root, such as 10, 16, 20, 40, and 80. There is no need to test every number through 80.
Choosing a Java Approach for Finding All Factors
The loop from 1 to num is the simplest approach to understand and is suitable when learning how the modulus operator identifies factors. When fewer divisibility checks are required, use factor pairs and stop at the square root of the number. For perfect squares, make sure the square-root factor is not added twice.
In this Java Tutorial, we learned how to find all the factors of a number, with the help of detailed Java Programs.
TutorialKart.com