Minimize Nth term of an Arithmetic progression ( AP ) | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNth ( int A , int B , int N ) { int res = INT_MAX ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = N ; j > i ; j -- ) { if ( ( B - A ) % ( j - i ) == 0 ) { int D = ( B - A ) / ( j - i ) ; int FirstTerm = A - ( i - 1 ) * D ; int NthTerm = FirstTerm + ( N - 1 ) * D ; if ( FirstTerm > 0 ) res = min ( res , NthTerm ) ; } } } return res ; } int main ( ) { int N = 3 ; int A = 1 ; int B = 6 ; cout << smallestNth ( A , B , N ) ; }