VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-print-factors-of-a-number-in-pairs/

⇱ Program to print factors of a number in pairs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to print factors of a number in pairs

Last Updated : 2 May, 2025

Given a number n, the task of the programmer is to print the factors of the number in such a way that they occur in pairs. A pair signifies that the product of the pair should result in the number itself.

Examples: 

Input : 24
Output : 1*24
2*12
3*8
4*6
Input : 50
Output : 1*50
2*25
5*10

The simplest approach for this program is that we run a loop from 1 to the square root of N and print and print 'i' and 'N%i' if the number N is dividing 'i'. 
The mathematical reason why we run the loop till square root of N is given below:
If a*b = N where 1 < a ≤ b < N
N = ab ≥ a^2 ⇔ a^2 ≤ N ⇔ a ≤ √N


Output
1*24
2*12
3*8
4*6

Time Complexity: O(sqrt(n)) where n is given number
Auxiliary Space: O(1)

Approach#2: Using for loop

The program first defines a function print_factor_pairs that takes a positive integer num as input. The function generates all factors of num using a list comprehension that loops through all numbers from 1 to the square root of num, and appends the pair (i, num//i) to a list if num is divisible by i. The function then iterates through the list of factor pairs and prints them in the format "i*j". In the main code, the user inputs a number and calls the print_factor_pairs function with that number as input.

Algorithm

1. Define a function print_factor_pairs that takes a positive integer num as input.
2. Generate all factors of num using a list comprehension that loops through all numbers from 1 to the square root of num, and appends the pair (i, num//i) to a list if num is divisible by i.
3. Iterate through the list of factor pairs and print them in the format "i*j".
4. In the main code, input a number from the user and call the print_factor_pairs function with that number as input.


Output
1*24
2*12
3*8
4*6

Time complexity:  O(sqrt(num)) because the loop only goes up to the square root of num.
The time complexity of iterating through the list of factor pairs and printing them is O(sqrt(num)) because there are sqrt(num) factor pairs.

Space complexity: O(sqrt(num)) because the list of factor pairs generated by the program has at most sqrt(num) elements.

Comment
Article Tags: