Construct an AP series consisting of A and B having minimum possible Nth term | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check_both_present ( int arr [ ] , int N , int a , int b ) { bool f1 = false , f2 = false ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == a ) { f1 = true ; } if ( arr [ i ] == b ) { f2 = true ; } } if ( f1 && f2 ) { return true ; } else { return false ; } } void print_array ( int ans [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } void build_AP ( int N , int a , int b ) { int arr [ N ] , ans [ N ] ; for ( int i = 0 ; i < N ; i ++ ) ans [ i ] = INT_MAX ; int flag = 0 ; if ( a > b ) { swap ( a , b ) ; } int diff = b - a ; for ( int start = 1 ; start <= a ; start ++ ) { for ( int d = 1 ; d <= diff ; d ++ ) { arr [ 0 ] = start ; for ( int i = 1 ; i < N ; i ++ ) { arr [ i ] = arr [ i - 1 ] + d ; } if ( check_both_present ( arr , N , a , b ) && arr [ N - 1 ] < ans [ N - 1 ] ) { for ( int i = 0 ; i < N ; i ++ ) { ans [ i ] = arr [ i ] ; } } } } print_array ( ans , N ) ; } int main ( ) { int N = 5 , A = 20 , B = 50 ; build_AP ( N , A , B ) ; return 0 ; }