Algorithms only:
def sumeven (n):
if n <= 0:
return 0
if n is even:
return n + sumeven (n-1)
return sumeven (n-1)
As with all recursive problems, break it down into:
- the terminating (lowest-level) value.
- all other values defined in terms of a "lower-level" value.
In the above case, the rules are:
f(0) is 0.
f(n) is f(n-1) for all odd values of n.
f(n) is n + f(n-1) for all even values of n.
This can be optimised to skip odd values (other than the first), if necessary, by changing that last rule to:
f(n) is n + f(n-2) for all even values of n.
giving the algorithm:
def sumeven (n):
if n <= 0:
return 0
if n is odd:
return sumeven (n-1)
return n + sumeven (n-2)