Factor Pairs in Java

Print all factor pairs (i, n/i) of a given number.

IntermediateModule 3: Loop ProgramsExample 20 of 25
factor-pairs.java
1import java.util.Scanner;
2
3public class Main {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7 int n = sc.nextInt();
8
9 for (int i = 1; i * i <= n; i++) {
10 if (n % i == 0) {
11 System.out.println(i + " x " + (n / i));
12 }
13 }
14 sc.close();
15 }
16}

Output

Enter a number: 12
1 x 12
2 x 6
3 x 4

What's going on

We only loop up to √n and print factor pairs when i divides n.