Java Program to Find Factors of a Number
for loop from 1 to the number and check if the number is divisible by the loop variable using if (number % i == 0) to print the factors.Examples
How to Think About It
Algorithm
Code
import java.util.Scanner; public class Factors { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); System.out.print("Factors of " + number + " are: "); for (int i = 1; i <= number; i++) { if (number % i == 0) { System.out.print(i + " "); } } sc.close(); } }
Dry Run
Let's trace the input 6 through the code to find its factors.
Input number
User enters number = 6
Start loop
Loop variable i starts at 1
Check divisibility
Check if 6 % i == 0 for i = 1 to 6
Print factors
Print i when condition is true: 1, 2, 3, 6
End loop
Loop ends after i = 6
| i | 6 % i | Is factor? |
|---|---|---|
| 1 | 0 | Yes |
| 2 | 0 | Yes |
| 3 | 0 | Yes |
| 4 | 2 | No |
| 5 | 1 | No |
| 6 | 0 | Yes |
Why This Works
Step 1: Loop through numbers
We use a for loop to check every number from 1 to the input number because factors must be within this range.
Step 2: Check divisibility
Using number % i == 0 checks if the remainder is zero, meaning i divides the number exactly.
Step 3: Print factors
When the condition is true, we print i as a factor because it divides the number evenly.
Alternative Approaches
import java.util.Scanner; public class FactorsWhile { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); int i = 1; System.out.print("Factors of " + number + " are: "); while (i <= number) { if (number % i == 0) { System.out.print(i + " "); } i++; } sc.close(); } }
import java.util.Scanner; public class FactorsOptimized { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); System.out.print("Factors of " + number + " are: "); for (int i = 1; i <= Math.sqrt(number); i++) { if (number % i == 0) { System.out.print(i + " "); if (i != number / i) { System.out.print((number / i) + " "); } } } sc.close(); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks every number from 1 to n, so it runs in linear time O(n).
Space Complexity
It uses only a few variables and prints output directly, so space is constant O(1).
Which Approach is Fastest?
The optimized approach checking up to square root of n reduces time to O(√n), which is faster for large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple for loop | O(n) | O(1) | Small to medium numbers |
| While loop | O(n) | O(1) | Same as for loop, different style |
| Optimized sqrt loop | O(√n) | O(1) | Large numbers for better performance |
number % i == 0 to find factors.