GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Calculate the series sum with given constraints

Calculate 1+2+…+n without multiplication, division, key words for, while, if, else,switch, case, as well as conditional operator (A ? B : C).

asked Nov 9, 2015 by Swanky

1 Answer

If we use a recursive function, we need to use key word if or conditional operators to check whether we should continue or stop recursion. Unfortunately, both of them are also forbidden.
We can also utilize compiler to simulate recursive calculate. Let us have a look at the following code:

The value of Sum<100>::N is the result of 1+2+…+100. When compilers see Sum<100>, it will generate code for the template class Sum with parameter 100. A class Sum <99> is needed to generate the class Sum<100> since Sum<100>::N = Sum <99>::N+100. The recursive process stops when it reaches the Sum<1> because it has been defined explicitly.

template <unsigned int n> struct Sum
{
    enum Value { N = Sum_Solution<n - 1>::N + n};
};


template <> struct Sum<1>
{
    enum Value { N = 1};
};

In the solution, the input n must be a constant value since calculations are all in compiling time. It is a big short coming for this solution. Additionally, n cannot be a large number since compilers have limitations on the depths of recursive compiling.

answered Nov 9, 2015 by Gaurav
...