Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write 2**n - 1 as a recursive function?

I need a function that takes n and returns 2n - 1 . It sounds simple enough, but the function has to be recursive. So far I have just 2n:

def required_steps(n):     if n == 0:         return 1     return 2 * req_steps(n-1) 

The exercise states: "You can assume that the parameter n is always a positive integer and greater than 0"

like image 999
Kajice Avatar asked Oct 14 '19 14:10

Kajice


People also ask

What is recursive function example?

Simple examples of a recursive function include the factorial, where an integer is multiplied by itself while being incrementally lowered. Many other self-referencing functions in a loop could be called recursive functions, for example, where n = n + 1 given an operating range.

What is a recursive function 2 points?

Explanation: The appropriate definition for a recursive function is a function execution instance that calls another execution instance of the same function either directly or indirectly. 2. Only problems that are recursively defined can be solved using recursion.


1 Answers

2**n -1 is also 1+2+4+...+2n-1 which can made into a single recursive function (without the second one to subtract 1 from the power of 2).

Hint: 1+2*(1+2*(...))

Solution below, don't look if you want to try the hint first.


This works if n is guaranteed to be greater than zero (as was actually promised in the problem statement):

def required_steps(n):     if n == 1: # changed because we need one less going down         return 1     return 1 + 2 * required_steps(n-1) 

A more robust version would handle zero and negative values too:

def required_steps(n):     if n < 0:         raise ValueError("n must be non-negative")     if n == 0:         return 0     return 1 + 2 * required_steps(n-1) 

(Adding a check for non-integers is left as an exercise.)

like image 130
h4z3 Avatar answered Sep 22 '22 20:09

h4z3