Sum of elements of a Geometric Progression ( GP ) in a given range | Java program to find the sum of elements of an GP in the given range ; Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int findSum ( int [ ] arr , int n , int left , int right ) { int k = right - left + 1 ; int d = arr [ 1 ] / arr [ 0 ] ; int ans = arr [ left - 1 ] ; if ( d == 1 ) ans = ans * d * k ; else ans = ans * ( ( int ) Math . pow ( d , k ) - 1 / ( d - 1 ) ) ; return ans ; } public static void main ( String args [ ] ) { int [ ] arr = { 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 } ; int queries = 3 ; int [ ] [ ] q = { { 2 , 4 } , { 2 , 6 } , { 5 , 8 } } ; int n = arr . length ; for ( int i = 0 ; i < queries ; i ++ ) System . out . println ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) ; } }