系统会为您提供一系列数字,从较低的数字到较高的数字(包括两端)。考虑除1以外的所有这些因素,任务是找到出现次数最多的因素。如果一个以上的数字具有最大频率,则不打印任何一个。
例子:
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.
解释:
如果我们有一个范围为10到14的数字,那么除1以外的其他因素将是:
- 10 => 2,5,10
- 11 => 11
- 12 => 2、3、4、6、12
- 13 => 13
- 14 => 2,7,14
在上述情况下,频率(2)= 3,这是与其他因素相比最大的。
方法:
1.如果lower = high,则所有因数都将具有频率1。因此,我们可以打印任何数字作为因数,因为每个数字都是其自身的因数,因此我们将打印相同的数字。
2.否则,我们将打印“ 2”,因为它在一定范围的数字中始终为真。
C++
// CPP program to find most common factor
// in a range.
#include
using namespace std;
int mostCommon(int lower, int higher)
{
// Check whether lower number
// and higher number are same
if (lower == higher)
return lower;
else
return 2;
}
// Driver Code
int main()
{
int lower = 10; // Lower number
int higher = 20; // Higher number
printf("The most frequent factor %d\n",
mostCommon(lower, higher));
return 0;
}
Java
// Java program to find most common factor
// in a range.
public class GfG {
public static int mostCommon(int lower, int higher)
{
// Check whether lower number
// and higher number are same
if (lower == higher)
return lower;
else
return 2;
}
// Driver code
public static void main(String []args) {
int lower = 10; // Lower number
int higher = 20; // Higher number
System.out.println("The most frequent factor " +
mostCommon(lower, higher));
}
}
// This code is contributed by Rituraj Jain
Python 3
# Python 3 program to find most
# common factor in a range.
def mostCommon( lower, higher):
# Check whether lower number
# and higher number are same
if (lower == higher):
return lower
else:
return 2
# Driver Code
lower = 10 # Lower number
higher = 20 # Higher number
print("The most frequent factor",
mostCommon(lower, higher))
# This code is contributed by ash264
C#
// C# program to find most common factor
// in a range.
using System;
class GFG
{
static int mostCommon(int lower, int higher)
{
// Check whether lower number
// and higher number are same
if (lower == higher)
return lower;
else
return 2;
}
// Driver Code
public static void Main()
{
int lower = 10; // Lower number
int higher = 20; // Higher number
Console.WriteLine("The most frequent factor " +
mostCommon(lower, higher));
}
}
// This code is contributed
// by Akanksha Rai
PHP
Javascript
输出:
The most frequent factor 2
时间复杂度: O(1)