Minimize Nth term of an Arithmetic progression ( AP ) | 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
function smallestNth ( A , B , N ) { let res = Number . MAX_VALUE ; for ( let i = 1 ; i < N ; i ++ ) { for ( let j = N ; j > i ; j -- ) { if ( ( B - A ) % ( j - i ) == 0 ) { let D = ( B - A ) / ( j - i ) ; let FirstTerm = A - ( i - 1 ) * D ; let NthTerm = FirstTerm + ( N - 1 ) * D ; if ( FirstTerm > 0 ) res = Math . min ( res , NthTerm ) ; } } } return res ; } let N = 3 ; let A = 1 ; let B = 6 ; document . write ( smallestNth ( A , B , N ) ) ;