Ways to express a number as product of two different factors
Last Updated :
17 Feb, 2023
Given a number n, write a program to calculate the number of ways in which numbers can be expressed as the product of two different factors.
Examples:
Input : 12
Output : 3
12 can be expressed as 1 * 12, 2 * 6 and 3*4.
Input : 36
Output : 4
36 can be expressed as 1 * 36, 2 * 18, 3 * 12 and 4 * 9.
All factors of 12 are = 1, 2, 3, 4, 6, 12
We can observe that factors always exist in
pair which is equal to number.
Here (1, 12), (2, 6) and (3, 4) are such pairs.
As a number can be expressed as the product of two factors we only need to find the number of factors of number up to the square root of the number. And we only need to find only different pairs so in the case of a perfect square we don’t include that factor.
C++
#include <bits/stdc++.h>
using namespace std;
int countWays( int n)
{
int count = 0;
for ( int i = 1; i * i < n; i++)
if (n % i == 0)
count++;
return count;
}
int main()
{
int n = 12;
cout << countWays(n) << endl;
return 0;
}
|
Java
public class Main {
static int countWays( int n)
{
int count = 0 ;
for ( int i = 1 ; i * i < n; i++)
if (n % i == 0 )
count++;
return count;
}
public static void main(String[] args)
{
int n = 12 ;
System.out.println(countWays(n));
}
}
|
Python 3
def countWays(n):
count = 0
i = 1
while ((i * i)<n) :
if (n % i = = 0 ):
count + = 1
i + = 1
return count
n = 12
print (countWays(n))
|
C#
using System;
public class main {
static int countWays( int n)
{
int count = 0;
for ( int i = 1; i * i < n; i++)
if (n % i == 0)
count++;
return count;
}
public static void Main()
{
int n = 12;
Console.WriteLine(countWays(n));
}
}
|
PHP
<?php
function countWays( $n )
{
$count = 0;
for ( $i = 1; $i * $i < $n ; $i ++)
if ( $n % $i == 0)
$count ++;
return $count ;
}
$n = 12;
echo countWays( $n ), "\n" ;
?>
|
Javascript
<script>
function countWays(n)
{
let count = 0;
for (let i = 1; i * i < n; i++)
if (n % i == 0)
count++;
return count;
}
let n = 12;
document.write(countWays(n));
</script>
|
Output:
3
Time Complexity: O(?n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...