Sum of P terms of an AP if Mth and Nth terms are given | Java 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 ; Driver Code
import java . util . * ; class GFG { static ArrayList < Integer > findingValues ( int m , int n , int mth , int nth ) { int d = ( Math . abs ( mth - nth ) ) / Math . abs ( ( m - 1 ) - ( n - 1 ) ) ; int a = mth - ( ( m - 1 ) * d ) ; ArrayList < Integer > res = new ArrayList < Integer > ( ) ; res . add ( a ) ; res . add ( d ) ; return res ; } static int findSum ( int m , int n , int mth , int nth , int p ) { ArrayList < Integer > ad = findingValues ( m , n , mth , nth ) ; int a = ad . get ( 0 ) ; int d = ad . get ( 1 ) ; int sum = ( p * ( 2 * a + ( p - 1 ) * d ) ) / 2 ; return sum ; } public static void main ( String [ ] args ) { int m = 6 , n = 10 , mTerm = 12 , nTerm = 20 , p = 5 ; System . out . println ( findSum ( m , n , mTerm , nTerm , p ) ) ; } }