Program to print factors of a number in pairs

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

C++

// CPP program to print prime factors in
// pairs.
#include <iostream>
using namespace std;
  
void printPFsInPairs(int n)
{
    for (int i = 1; i * i <= n; i++)
        if (n % i == 0)
            cout << i << "*" << n / i << endl;
}
  
// Driver code
int main()
{
    int n = 24;
    printPFsInPairs(n);
    return 0;
}

Java

// Java program to print prime factors in
// pairs.
public class GEE {
  
    static void printPFsInPairs(int n)
    {
        for (int i = 1; i * i <= n; i++)
            if (n % i == 0)
                System.out.println(i + "*" + n / i);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int n = 24;
        printPFsInPairs(n);
    }
}

C#

// C# program to print prime factors in
// pairs.
using System;
public class GEE {
  
    static void printPFsInPairs(int n)
    {
        for (int i = 1; i * i <= n; i++)
            if (n % i == 0)
                Console.Write(i + "*" + n / i + "\n");
    }
  
    // Driver code
    public static void Main()
    {
  
        int n = 24;
        printPFsInPairs(n);
    }
}

Python 3

# Python 3 program to print prime factors in
# pairs.
   
def printPFsInPairs(n): 
    for i in range(1, int(pow(n, 1 / 2))+1):
        if n % i == 0:
            print(str(i) +"*"+str(int(n / i)))   
   
# Driver code
n = 24
printPFsInPairs(n)

PHP

<?php
// PHP program to print prime factors in
// pairs.
   
function printPFsInPairs($n
{
    for ($i = 1; $i*$i <= $n; $i++) 
        if ($n % $i == 0) 
            echo $i."*". $n / $i ."\n";    
}
   
// Driver code
$n = 24;
printPFsInPairs($n);
return 0;
?>

Output:

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


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ChitraNayal

Article Tags :
Practice Tags :



Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.