Sum of range in a series of first odd then even natural numbers | 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
< ? php function sumTillX ( $ x , $ n ) { $ odd = ceil ( $ n / 2.0 ) ; if ( $ x <= $ odd ) return $ x * $ x ; $ even = $ x - $ odd ; return ( ( $ odd * $ odd ) + ( $ even * $ even ) + $ even ) ; } function rangeSum ( $ N , $ L , $ R ) { return sumTillX ( $ R , $ N ) - sumTillX ( $ L - 1 , $ N ) ; } $ N = 10 ; $ L = 1 ; $ R = 6 ; echo ( rangeSum ( $ N , $ L , $ R ) ) ; ? >