Sum of N | C ++ implementation to illustrate the program ; Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to print the value of Sum ; Driver Code ; First element ; Common difference ; Number of elements ; Mod value
#include <iostream> NEW_LINE using namespace std ; int SumGPUtil ( long long int r , long long int n , long long int m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; long long int 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 ) ; } void SumGP ( long long int a , long long int r , long long int N , long long int M ) { long long int answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; cout << answer << endl ; } int main ( ) { long long int a = 1 ; long long int r = 4 ; long long int N = 10000 ; long long int M = 100000 ; SumGP ( a , r , N , M ) ; return 0 ; }