Greatest divisor which divides all natural number in range [L, R]
Given two integers L and R, the task is to find the greatest divisor that divides all the natural numbers in the range [L, R].
Examples:
Input: L = 3, R = 12
Output: 1
Input: L = 24, R = 24
Output: 24
Approach: For a range of consecutive integer elements, there are two cases:
- If L = R then the answer will L.
- If L < R then all consecutive natural numbers in this range are co-primes. So, 1 is the only number that will be able to divide all the elements of the range.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int find_greatest_divisor( int l, int r)
{
if (l == r)
return l;
return 1;
}
int main()
{
int l = 2, r = 12;
cout << find_greatest_divisor(l, r);
}
|
C
#include <stdio.h>
int find_greatest_divisor( int l, int r)
{
if (l == r)
return l;
return 1;
}
int main()
{
int l = 2, r = 12;
printf ( "%d" ,find_greatest_divisor(l, r));
}
|
Java
class GFG {
static int find_greatest_divisor( int l, int r) {
if (l == r) {
return l;
}
return 1 ;
}
public static void main(String[] args) {
int l = 2 , r = 12 ;
System.out.println(find_greatest_divisor(l, r));
}
}
|
Python3
def find_greatest_divisor(l, r):
if (l = = r):
return l;
return 1 ;
l = 2 ;
r = 12 ;
print (find_greatest_divisor(l, r));
|
C#
using System;
class GFG {
static int find_greatest_divisor( int l, int r) {
if (l == r) {
return l;
}
return 1;
}
public static void Main() {
int l = 2, r = 12 ;
Console.WriteLine(find_greatest_divisor(l, r));
}
}
|
PHP
<?php
function find_greatest_divisor( $l , $r )
{
if ( $l == $r )
return $l ;
return 1;
}
$l = 2;
$r = 12;
echo find_greatest_divisor( $l , $r );
?>
|
Javascript
<script>
function find_greatest_divisor(l, r)
{
if (l == r)
return l;
return 1;
}
let l = 2;
let r = 12;
document.write( find_greatest_divisor(l, r));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
23 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...