Factor Pairs
Print all factor pairs (i, n/i) of a given number.
IntermediateTopic: Module 3: Loop Programs
Java Factor Pairs Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
System.out.println(i + " x " + (n / i));
}
}
sc.close();
}
}Output
Enter a number: 12 1 x 12 2 x 6 3 x 4
Understanding Factor Pairs
We only loop up to √n and print factor pairs when i divides n.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.