VOOZH about

URL: https://www.geeksforgeeks.org/dsa/gcd-elements-given-range/

⇱ GCD of elements in a given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

GCD of elements in a given range

Last Updated : 16 Jun, 2022

Given two numbers n and m. Find the biggest integer a(gcd), such that all integers n, n + 1, n + 2, ..., m are divisible by a.
Examples: 
 

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.


 


Here, We have to examine only two cases: 
 

  1. if a = b : the segment consists of a single number, hence the answer is a.
  2. if a < b : we have gcd(n, n + 1, n?+ 2, ..., m) = gcd(gcd(n, n + 1), n + 2, ..., m) = gcd(1, n + 2, ..., n) = 1.

Output:

475

Time Complexity: O(1)

Auxiliary Space: O(1)

Comment
Article Tags: