Sum of N | Java implementation to illustrate the program ; Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to prlong the value of Sum ; Driver Code ; First element ; Common difference ; Number of elements ; Mod value
import java . io . * ; class GFG { static long SumGPUtil ( long r , long n , long m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; long ans ; if ( n % 2 == 1 ) { ans = ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n - 1 ) / 2 , m ) ; } else { ans = 1 + ( r * ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n / 2 ) - 1 , m ) ) ; } return ( ans % m ) ; } static void SumGP ( long a , long r , long N , long M ) { long answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; System . out . println ( answer ) ; } public static void main ( String [ ] args ) { long a = 1 ; long r = 4 ; long N = 10000 ; long M = 100000 ; SumGP ( a , r , N , M ) ; } }