Largest number in [ 2 , 3 , . . n ] which is co | Java Largest number in [ 2 , 3 , . . n ] which is co - prime with numbers in [ 2 , 3 , . . m ] ; Returns true if i is co - prime with numbers in set [ 2 , 3 , ... m ] ; Running the loop till square root of n to reduce the time complexity from n ; Find the minimum of square root of n and m to run the loop until the smaller one ; Check from 2 to min ( m , sqrt ( n ) ) ; Function to find the largest number less than n which is Co - prime with all numbers from 2 to m ; Iterating from n to m + 1 to find the number ; checking every number for the given conditions ; The first number which satisfy the conditions is the answer ; If there is no number which satisfy the conditions , then print number does not exist . ; Driver Program
import java . io . * ; class GFG { static boolean isValid ( long i , long m ) { long sq_i = ( long ) Math . sqrt ( i ) ; long sq = Math . min ( m , sq_i ) ; for ( long j = 2 ; j <= sq ; j ++ ) if ( i % j == 0 ) return false ; return true ; } static void findLargestNum ( long n , long m ) { for ( long i = n ; i > m ; i -- ) { if ( isValid ( i , m ) ) { System . out . println ( i ) ; return ; } } System . out . println ( " Number ▁ Doesn ' t ▁ Exists " ) ; } public static void main ( String [ ] args ) { long n = 16 , m = 3 ; findLargestNum ( n , m ) ; } }