Minimize Nth term of an Arithmetic progression ( AP ) | Python3 program to implement the above approach ; Function to find the smallest Nth term of an AP possible ; Stores the smallest Nth term ; Check if common difference of AP is an integer ; Store the common difference ; Store the First Term of that AP ; Store the Nth term of that AP ; Check if all elements of an AP are positive ; Return the least Nth term obtained ; Driver Code
import sys NEW_LINE def smallestNth ( A , B , N ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( N , i , - 1 ) : NEW_LINE INDENT if ( ( B - A ) % ( j - i ) == 0 ) : NEW_LINE INDENT D = ( B - A ) // ( j - i ) NEW_LINE FirstTerm = A - ( i - 1 ) * D NEW_LINE NthTerm = FirstTerm + ( N - 1 ) * D NEW_LINE if ( FirstTerm > 0 ) : NEW_LINE INDENT res = min ( res , NthTerm ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE A = 1 NEW_LINE B = 6 NEW_LINE print ( smallestNth ( A , B , N ) ) NEW_LINE DEDENT