Skip to content
Related Articles

Related Articles

Program to print factors of a number in pairs
  • Last Updated : 12 Apr, 2021

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;
?>

Javascript




<script>
 
// Javascript program to print prime factors in
// pairs.
 
function printPFsInPairs(n)
{
    for (let i = 1; i * i <= n; i++)
        if (n % i == 0)
            document.write(i + "*" + parseInt(n / i) + "<br>");
}
 
// Driver code
let n = 24;
printPFsInPairs(n);
 
</script>
Output: 
1*24
2*12
3*8
4*6

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :