Construct an AP series consisting of A and B having minimum possible Nth term | Python3 program for the above approach ; Function to check if both a and b are present in the AP series or not ; Iterate over the array arr [ ] ; If a is present ; If b is present ; If both are present ; Otherwise ; Function to print all the elements of the Arithmetic Progression ; Function to construct AP series consisting of A and B with minimum Nth term ; Stores the resultant series ; Initialise ans [ i ] as INT_MAX ; Maintain a smaller than b ; Swap a and b ; Difference between a and b ; Check for all possible combination of start and common difference d ; Initialise arr [ 0 ] as start ; Check if both a and b are present or not and the Nth term is the minimum or not ; Update the answer ; Print the resultant array ; Driver Code ; Function call
import sys NEW_LINE def check_both_present ( arr , N , a , b ) : NEW_LINE INDENT f1 = False NEW_LINE f2 = False NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if arr [ i ] == a : NEW_LINE INDENT f1 = True NEW_LINE DEDENT if arr [ i ] == b : NEW_LINE INDENT f2 = True NEW_LINE DEDENT DEDENT if f1 and f2 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def print_array ( ans , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def build_AP ( N , a , b ) : NEW_LINE INDENT INT_MAX = sys . maxsize NEW_LINE arr = [ None for i in range ( N ) ] NEW_LINE ans = [ INT_MAX for i in range ( N ) ] NEW_LINE flag = 0 NEW_LINE if a > b : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT diff = b - a NEW_LINE for start in range ( 1 , a + 1 ) : NEW_LINE INDENT for d in range ( 1 , diff + 1 ) : NEW_LINE INDENT arr [ 0 ] = start NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] + d NEW_LINE DEDENT if ( ( check_both_present ( arr , N , a , b ) and arr [ N - 1 ] < ans [ N - 1 ] ) ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT ans [ i ] = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT print_array ( ans , N ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE A = 20 NEW_LINE B = 50 NEW_LINE build_AP ( N , A , B ) NEW_LINE DEDENT