📜  将所有自然数除以 [L, R] 范围内的最大除数

📅  最后修改于: 2021-10-27 06:24:41             🧑  作者: Mango

给定两个整数LR ,任务是找到能整除[L, R]范围内所有自然数的最大除数。
例子:

处理方式:对于一系列连续的整数元素,有两种情况:

  • 如果L = R那么答案是L
  • 如果L < R,则此范围内的所有连续自然数都是互质数。因此, 1是唯一能够划分范围内所有元素的数字。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the greatest divisor that
// divides all the natural numbers in the range [l, r]
int find_greatest_divisor(int l, int r)
{
    if (l == r)
        return l;
 
    return 1;
}
 
// Driver Code
int main()
{
    int l = 2, r = 12;
 
    cout << find_greatest_divisor(l, r);
}


Java
// Java implementation of the approach
 
class GFG {
 
// Function to return the greatest divisor that
// divides all the natural numbers in the range [l, r]
    static int find_greatest_divisor(int l, int r) {
        if (l == r) {
            return l;
        }
 
        return 1;
    }
 
// Driver Code
    public static void main(String[] args) {
        int l = 2, r = 12;
 
        System.out.println(find_greatest_divisor(l, r));
    }
}
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation of the approach
 
# Function to return the greatest divisor that
# divides all the natural numbers in the range [l, r]
def find_greatest_divisor(l, r):
 
    if (l == r):
        return l;
 
    return 1;
 
 
# Driver Code
 
l = 2;
r = 12;
 
print(find_greatest_divisor(l, r));
 
#This code is contributed by Shivi_Aggarwal


C#
// C# implementation of the approach
using System;
 
class GFG {
 
    // Function to return the greatest divisor that
    // divides all the natural numbers in the range [l, r]
    static int find_greatest_divisor(int l, int r) {
        if (l == r) {
            return l;
        }
 
        return 1;
    }
 
    // Driver Code
    public static void Main() {
        int l = 2,  r = 12 ;
 
        Console.WriteLine(find_greatest_divisor(l, r));
    }
    // This code is contributed by Ryuga
 
}


PHP


Javascript


输出:
1

时间复杂度: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程