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++
#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;
}
int main()
{
int n = 24;
printPFsInPairs(n);
return 0;
}
|
Java
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);
}
public static void main(String[] args)
{
int n = 24 ;
printPFsInPairs(n);
}
}
|
C#
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" );
}
public static void Main()
{
int n = 24;
printPFsInPairs(n);
}
}
|
Python 3
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)))
n = 24
printPFsInPairs(n)
|
PHP
<?php
function printPFsInPairs( $n )
{
for ( $i = 1; $i * $i <= $n ; $i ++)
if ( $n % $i == 0)
echo $i . "*" . $n / $i . "\n" ;
}
$n = 24;
printPFsInPairs( $n );
return 0;
?>
|
Javascript
<script>
function printPFsInPairs(n)
{
for (let i = 1; i * i <= n; i++)
if (n % i == 0)
document.write(i + "*" + parseInt(n / i) + "<br>" );
}
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.