📜  给定范围内的元素的GCD

📅  最后修改于: 2021-04-26 08:43:45             🧑  作者: Mango

给定两个数字n和m。找出最大的整数a(gcd),以使所有整数n,n + 1,n + 2,…,m可被a整除。

例子:

Input : n = 1, m = 2
Output: 1
Explanation:
Here, series become 1, 2. So, the 
greatest no which divides both of 
them is 1.

Input : n = 475, m = 475
Output : 475
Explanation:
Here, series has only one term 475.
So, greatest no which divides 475 is 475.

在这里,我们只需要检查两种情况:

  1. 如果a = b:该段由单个数字组成,则答案为a。
  2. 如果a 下面是上述方法的代码。

    C++
    // GCD of given range
    #include 
    using namespace std;
      
    int rangeGCD(int n, int m)
    {
        return (n == m)? n : 1;
    }
      
    int main()
    {
        int n = 475;
        int m = 475;
        cout << rangeGCD(n, m);
        return 0;
    }


    Java
    // GCD of given range
      
    import java.io.*;
      
    class GFG {
      
        static int rangeGCD(int n, int m)
        {
            return (n == m) ? n : 1;
        }
      
        public static void main(String[] args)
        {
            int n = 475;
            int m = 475;
              
            System.out.println(rangeGCD(n, m));
        }
    }
      
    // This code is contributed by Ajit.


    Python3
    # GCD of given range
      
    def rangeGCD(n, m):
        return n if(n == m) else 1
          
    # Driver code
    n, m = 475, 475
    print(rangeGCD(n, m))
      
    # This code is contributed by Anant Agarwal.


    C#
    // GCD of given range
    using System;
       
    class GFG {
       
        static int rangeGCD(int n, int m)
        {
            return (n == m) ? n : 1;
        }
       
        public static void Main()
        {
            int n = 475;
            int m = 475;
               
            Console.WriteLine(rangeGCD(n, m));
        }
    }
       
    // This code is contributed by Anant Agarwal.


    PHP


    输出:

    475