Length of smallest sequence having sum X and product Y | Java program for the above approach ; Function for checking valid or not ; Function for checking boundary of binary search ; Function to calculate the minimum sequence size using binary search ; Initialize high and low ; Base case ; Print - 1 if a sequence cannot be generated ; Otherwise ; Iterate until difference between high and low exceeds 1 ; Calculate mid ; Reset values of high and low accordingly ; Print the answer ; Driver Code ; Function call
import java . util . * ; class GFG { static double temp ( int n , int x ) { return Math . pow ( x * 1.0 / n , n ) ; } static boolean check ( int n , int y , int x ) { double v = temp ( n , x ) ; return ( v >= y ) ; } static void find ( int x , int y ) { int high = ( int ) Math . floor ( x / Math . exp ( 1.0 ) ) ; int low = 1 ; if ( x == y ) System . out . print ( 1 + "NEW_LINE"); else if ( ! check ( high , y , x ) ) System . out . print ( - 1 + "NEW_LINE"); else { while ( high - low > 1 ) { int mid = ( high + low ) / 2 ; if ( check ( mid , y , x ) ) high = mid ; else low = mid ; } System . out . print ( high + "NEW_LINE"); } } public static void main ( String [ ] args ) { int x = 9 , y = 8 ; find ( x , y ) ; } }