Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Factor Pairs in Java

List factor pairs in Java with % and the safe i <= n / i loop limit. Scanner reads a positive integer; each pair prints once, including equal square factors.

IntermediateJava 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 <= n / i; i++) {
10 if (n % i == 0) {
11 System.out.println(i + " x " + (n / i));
12 }
13 }
14 sc.close();
15 }
16}

Sample Output

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

The successful trial values are i=1,2,3. Their partners are 12,6,4. The next trial would be past the square-root limit.

In this one

  • Find factors using zero remainder
  • Calculate the partner by division
  • Avoid duplicate reversed pairs

How it works

  1. 1

    Read positive n.

  2. 2

    Try i starting at 1 through the square-root limit.

  3. 3

    Check n % i == 0.

  4. 4

    Print i and n / i for each match.

Edge cases

Perfect square

Enter 36

The pair 6 x 6 appears once at the square-root limit.

Input one

Enter 1

The only pair is 1 x 1.

What's going on

Print pairs of whole numbers whose product equals the input. For 12, the pairs are 1 and 12, 2 and 6, and 3 and 4. This helps a student see how factors come in pairs before learning prime checks and common divisors.

Scanner is the keyboard reader. The loop tries i from 1 while i * i <= n. The % operator gives the remainder, the amount left after division. When n % i is zero, i is a factor and n / i gives its partner. Printing the pair together avoids a second search.

Only the smaller side of each pair is tried, so 4 x 3 is not printed again after 3 x 4. For a perfect square, the equal pair such as 6 x 6 prints once. The sample expects a positive number. For large int input, use a wider square test or i <= n / i to avoid exceeding the size of int in i * i.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the partner of 3 for n = 12?

Pick an answer to check it.

Question 2

Should 4 x 3 print after 3 x 4?

Pick an answer to check it.

Questions people ask

Why stop at the square root?

After that point, every pair would repeat a partner pair already found.

Does this list negative factor pairs?

No. It uses only positive i and is intended for positive n.

What if n is prime?

Only 1 x n is printed.