The Wayback Machine - https://web.archive.org/web/20230312091805/https://www.geeksforgeeks.org/practice-questions-for-recursion-set-2/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Practice Questions for Recursion | Set 2

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 20 Feb, 2023
Improve Article
Save Article

Explain the functionality of the following functions. 

Question 1 

C++




/* Assume that n is greater than or equal to 1 */
int fun1(int n)
{
    if (n == 1)
        return 0;
    else
        return 1 + fun1(n / 2);
}

Java




/* Assume that n is greater than or equal to 1 */
static int fun1(int n)
{
    if (n == 1)
        return 0;
    else
        return 1 + fun1(n / 2);
}

Python3




# Assume that n is greater than or equal to 1 */
def fun1(n):
    if(n == 1):
        return 0
    else:
        return 1 + fun1(n//2)

C#




/* Assume that n is greater than or equal to 1 */
static int fun1(int n)
{
    if (n == 1)
        return 0;
    else
        return 1 + fun1(n / 2);
}

Javascript




<script>
  
/* Assume that n is greater than or equal to 1 */
function fun1(n)
{
    if (n == 1)
        return 0
    else
        return 1 + fun1(Math.floor(n / 2))
}
</script>

Answer: The function calculates and returns log2floor

For example, if n is between 8 and 15 then fun1() returns 3. If n is between 16 to 31 then fun1() returns 4.

Question 2 

C++




/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
if(n == 0)
    return;
  
fun2(n/2);
cout << n%2 << endl;
}

C




/* Assume that n is greater than or equal to 0 */
void fun2(int n)
{
  if(n == 0)
    return;
  
  fun2(n/2);
  printf("%d", n%2);
}  

Java




/* Assume that n is greater than or equal to 1 */
static void fun2(int n)
{
if(n == 0)
    return;
   
fun2(n/2);
System.out.println(n%2);
} 

Python3




# Assume that n is greater than or equal to 0 */
def fun2(n):
    if(n == 0):
        return
      
    fun2(n // 2)
    print(n % 2, end="")

C#




void fun2(int n) 
{ 
if(n == 0) 
    return; 
    
fun2(n/2); 
Console.Write(n%2); 
} 

Javascript




<script>
  
// Assume that n is greater than or equal to 1 
function fun2(n)
{
    if (n == 0)
        return;
      
    fun2(Math.floor(n / 2));
    document.write(n % 2 + " ")
}
</script>

Auxiliary Space: O(log2N), due to recursion call stack

Answer: The function fun2() prints the binary equivalent of n. For example, if n is 21 then fun2() prints 10101. 

Note: Above functions are just for practicing recursion, they are not the ideal implementation of the functionality they provide. 

Please write comments if you find any of the answers/codes incorrect. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!