Sum of N | Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to prlet the value of Sum ; First element ; Common difference ; Number of elements ; Mod value
function SumGPUtil ( r , n , m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; let 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 ) ; } function SumGP ( a , r , N , M ) { let answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; document . write ( answer ) ; } let a = 1 ; let r = 4 ; let N = 10000 ; let M = 100000 ; SumGP ( a , r , N , M ) ;