Sum of P terms of an AP if Mth and Nth terms are given | C ++ implementation of the above approach ; Function to calculate the value of the ; Calculate value of d using formula ; Calculate value of a using formula ; Return pair ; Function to calculate value sum of first p numbers of the series ; First calculate value of a and d ; Calculate the sum by using formula ; Return the sum ; Driven Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < double , double > findingValues ( double m , double n , double mth , double nth ) { double d = ( abs ( mth - nth ) ) / abs ( ( m - 1 ) - ( n - 1 ) ) ; double a = mth - ( ( m - 1 ) * d ) ; return make_pair ( a , d ) ; } double findSum ( int m , int n , int mth , int nth , int p ) { pair < double , double > ad ; ad = findingValues ( m , n , mth , nth ) ; double a = ad . first , d = ad . second ; double sum = ( p * ( 2 * a + ( p - 1 ) * d ) ) / 2 ; return sum ; } int main ( ) { double m = 6 , n = 10 , mTerm = 12 , nTerm = 20 , p = 5 ; cout << findSum ( m , n , mTerm , nTerm , p ) << endl ; return 0 ; }