Most frequent factor in a range of integers
Last Updated :
19 Dec, 2022
You are given a range of numbers, from lower number to higher number (both inclusive). Consider all the factors of these numbers except 1, the task is to find the factor which appears the maximum number of times. If more than one number have maximum frequency then print anyone of them.
Examples:
Input : lower=10 higher=14
Output : The factor with maximum frequency is 2.
Input : lower=11 higher=11
Output : The factor with maximum frequency is 11.
Explanation:
If we have a range of numbers, say 10 to 14. Then the factors other than 1 will be:
- 10 => 2, 5, 10
- 11 => 11
- 12 => 2, 3, 4, 6, 12
- 13 => 13
- 14 => 2, 7, 14
In the above case, frequency(2)= 3, which is maximum on comparing with other factors.
Approach:
1. If lower = higher, then all factors will have frequency 1. So we can print any number which is factor, since every number is a factor of itself so we print the same number.
2. Otherwise, we print ‘2’ as it will always be true for a range of numbers.
C++
#include <bits/stdc++.h>
using namespace std;
int mostCommon( int lower, int higher)
{
if (lower == higher)
return lower;
else
return 2;
}
int main()
{
int lower = 10;
int higher = 20;
printf ( "The most frequent factor %d\n" ,
mostCommon(lower, higher));
return 0;
}
|
Java
public class GfG {
public static int mostCommon( int lower, int higher)
{
if (lower == higher)
return lower;
else
return 2 ;
}
public static void main(String []args) {
int lower = 10 ;
int higher = 20 ;
System.out.println( "The most frequent factor " +
mostCommon(lower, higher));
}
}
|
Python 3
def mostCommon( lower, higher):
if (lower = = higher):
return lower
else :
return 2
lower = 10
higher = 20
print ( "The most frequent factor" ,
mostCommon(lower, higher))
|
C#
using System;
class GFG
{
static int mostCommon( int lower, int higher)
{
if (lower == higher)
return lower;
else
return 2;
}
public static void Main()
{
int lower = 10;
int higher = 20;
Console.WriteLine( "The most frequent factor " +
mostCommon(lower, higher));
}
}
|
PHP
<?php
function mostCommon( $lower , $higher )
{
if ( $lower == $higher )
return $lower ;
else
return 2;
}
$lower = 10;
$higher = 20;
echo "The most frequent factor " .
mostCommon( $lower , $higher ) . "\n" ;
?>
|
Javascript
<script>
function mostCommon(lower , higher)
{
if (lower == higher)
return lower;
else
return 2;
}
var lower = 10;
var higher = 20;
document.write( "The most frequent factor " +
mostCommon(lower, higher));
</script>
|
Output:
The most frequent factor 2
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...