Arithmetic Progression containing X and Y with least possible first term | Function that finds the minimum positive first term including X with given common difference and the number of terms ; Stores the first term ; Initialize the low and high ; Perform binary search ; Find the mid ; Check if first term is greater than 0 ; Store the possible first term ; Search between mid + 1 to high ; Search between low to mid - 1 ; Return the minimum first term ; Function that finds the Arithmetic Progression with minimum possible first term containing X and Y ; Considering X to be smaller than Y always ; Stores the max common difference ; Stores the minimum first term and the corresponding common difference of the resultant AP ; Iterate over all the common difference ; Check if X and Y is included for current common difference ; Store the possible common difference ; Number of terms from X to Y with diff1 common difference ; Number of terms from X to Y with diff2 common difference ; Find the corresponding first terms with diff1 and diff2 ; Store the minimum first term and the corresponding common difference ; Prlet the resultant AP ; Given length of AP and the two terms ; Function call
function minFirstTerm ( X , diff , N ) { let first_term = Number . MAX_VALUE ; let low = 0 , high = N ; while ( low <= high ) { let mid = Math . floor ( ( low + high ) / 2 ) ; if ( X - mid * diff > 0 ) { first_term = X - mid * diff ; low = mid + 1 ; } else high = mid - 1 ; } return first_term ; } function prletAP ( N , X , Y ) { if ( X > Y ) { X = X + Y ; Y = X - Y ; X = X - Y ; } let maxDiff = Y - X ; let first_term = Number . MAX_VALUE , diff = 0 ; for ( let i = 1 ; i * i <= maxDiff ; i ++ ) { if ( maxDiff % i == 0 ) { let diff1 = i ; let diff2 = Math . floor ( maxDiff / diff1 ) ; let terms1 = diff2 + 1 ; let terms2 = diff1 + 1 ; let first_term1 = minFirstTerm ( X , diff1 , N - terms1 ) ; let first_term2 = minFirstTerm ( X , diff2 , N - terms2 ) ; if ( first_term1 < first_term ) { first_term = first_term1 ; diff = diff1 ; } if ( first_term2 < first_term ) { first_term = first_term2 ; diff = diff2 ; } } } for ( let i = 0 ; i < N ; i ++ ) { document . write ( first_term + " " ) ; first_term += diff ; } } let N = 5 , X = 10 , Y = 15 ; prletAP ( N , X , Y ) ;