Number which is co-prime with all integers from a given range
Last Updated :
06 May, 2022
Given two positive integers L and R, the task is to find an integer X greater than 1 such that X is co-prime with all the integers from the range [L, R].
Examples:
Input: L = 16, R = 17
Output: 19
Explanation: Only number which is co-prime with all the integers from the range [16, 17] is 9.
Input: L = 973360, R = 973432
Output: 973439
Approach: The simplest approach to solve the given problem is to find a prime number greater than R, because this integer does not divide any integer in the range of [L, R]. Therefore, the idea is to iterate from the value (R + 1) and if there exists any integer which is prime, then print that integer and break out of the loop.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime( int N)
{
if (N == 1)
return false ;
for ( int i = 2; i * i <= N; i++) {
if (N % i == 0)
return false ;
}
return true ;
}
int findCoPrime( int L, int R)
{
int coPrime;
for ( int i = R + 1;; i++) {
if (isPrime(i)) {
coPrime = i;
break ;
}
}
return coPrime;
}
int main()
{
int L = 16, R = 17;
cout << findCoPrime(L, R);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
static boolean isPrime( int N)
{
if (N == 1 )
return false ;
for ( int i = 2 ; i * i <= N; i++)
{
if (N % i == 0 )
return false ;
}
return true ;
}
static int findCoPrime( int L, int R)
{
int coPrime;
for ( int i = R + 1 ;; i++)
{
if (isPrime(i))
{
coPrime = i;
break ;
}
}
return coPrime;
}
public static void main(String[] args)
{
int L = 16 , R = 17 ;
System.out.println(findCoPrime(L, R));
}
}
|
Python3
def isPrime(N):
if (N = = 1 ):
return False
for i in range ( 2 , N + 1 ):
if i * i > N:
break
if (N % i = = 0 ):
return False
return True
def findCoPrime(L, R):
coPrime, i = 0 , R + 1
while True :
if (isPrime(i)):
coPrime = i
break
i + = 1
return coPrime
if __name__ = = '__main__' :
L,R = 16 , 17
print (findCoPrime(L, R))
|
C#
using System;
class GFG{
static bool isPrime( int N)
{
if (N == 1)
return false ;
for ( int i = 2; i * i <= N; i++)
{
if (N % i == 0)
return false ;
}
return true ;
}
static int findCoPrime( int L, int R)
{
int coPrime;
for ( int i = R + 1;; i++)
{
if (isPrime(i))
{
coPrime = i;
break ;
}
}
return coPrime;
}
public static void Main( string [] args)
{
int L = 16, R = 17;
Console.WriteLine(findCoPrime(L, R));
}
}
|
Javascript
<script>
function isPrime(N)
{
if (N == 1)
return false ;
for ( var i = 2; i * i <= N; i++)
{
if (N % i == 0)
return false ;
}
return true ;
}
function findCoPrime(L , R)
{
var coPrime;
for ( var i = R + 1;; i++)
{
if (isPrime(i))
{
coPrime = i;
break ;
}
}
return coPrime;
}
var L = 16, R = 17;
document.write(findCoPrime(L, R));
</script>
|
Time Complexity: O(L * R1/2)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...