Arithmetic Progression containing X and Y with least possible first term | Python3 program for the approach ; 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 ; Print the resultant AP ; Driver Code ; Given length of AP and the two terms ; Function call
import sys NEW_LINE def minFirstTerm ( X , diff , N ) : NEW_LINE INDENT first_term_1 = sys . maxsize NEW_LINE low = 0 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( X - mid * diff > 0 ) : NEW_LINE INDENT first_term_1 = X - mid * diff NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return first_term_1 NEW_LINE DEDENT def printAP ( N , X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT X = X + Y NEW_LINE Y = X - Y NEW_LINE X = X - Y NEW_LINE DEDENT maxDiff = Y - X NEW_LINE first_term = sys . maxsize NEW_LINE diff = 0 NEW_LINE for i in range ( 1 , maxDiff + 1 ) : NEW_LINE INDENT if i * i > maxDiff : NEW_LINE INDENT break NEW_LINE DEDENT if ( maxDiff % i == 0 ) : NEW_LINE INDENT diff1 = i NEW_LINE diff2 = maxDiff // diff1 NEW_LINE terms1 = diff2 + 1 NEW_LINE terms2 = diff1 + 1 NEW_LINE first_term1 = minFirstTerm ( X , diff1 , N - terms1 ) NEW_LINE first_term2 = minFirstTerm ( X , diff2 , N - terms2 ) NEW_LINE if ( first_term1 < first_term ) : NEW_LINE INDENT first_term = first_term1 NEW_LINE diff = diff1 NEW_LINE DEDENT if ( first_term2 < first_term ) : NEW_LINE INDENT first_term = first_term2 NEW_LINE diff = diff2 NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( first_term , end = " ▁ " ) NEW_LINE first_term += diff NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE X = 10 NEW_LINE Y = 15 NEW_LINE printAP ( N , X , Y ) NEW_LINE DEDENT