Sum of range in a series of first odd then even natural numbers | CPP program to find sum in the given range in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; Function that returns sum in the range 1 to x in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; number of odd numbers ; number of extra even numbers required ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long NEW_LINE ll sumTillX ( ll x , ll n ) { ll odd = ceil ( n / 2.0 ) ; if ( x <= odd ) return x * x ; ll even = x - odd ; return ( ( odd * odd ) + ( even * even ) + even ) ; } int rangeSum ( int N , int L , int R ) { return sumTillX ( R , N ) - sumTillX ( L - 1 , N ) ; } int main ( ) { ll N = 10 , L = 1 , R = 6 ; cout << rangeSum ( N , L , R ) ; return 0 ; }