Computer Science
Consider the following Python function Fn(), that follows:
def Fn(n):
print (n, end=" ")
if n < 3:
return n
else:
return Fn (n//2) - Fn (n//3)
What will be the result produced by the following function calls?
- Fn (12)
- Fn (10)
- Fn (7)
Answer
1.
12 6 3 1 1 2 4 2 1
2.
10 5 2 1 3 1 1
3.
7 3 1 1 2
Working
The provided code defines a recursive function Fn(n)
that prints the value of n
and then checks if n
is less than 3. If n
is less than 3, the function returns n
. Otherwise, it recursively calls itself with n//2
(integer division by 2) and subtracts the result of another recursive call with n//3
(integer division by 3).
Related Questions
Consider the following Python function that uses recursion.
def check (n) : if n <=1: return True elif n % 2 == 0: return check (n/2) else: return check (n/1)
What is the value returned by check(8) ?
Can you find an error or problem with the below code? Think about what happens if we evaluate check(3). What output would be produced by Python? Explain the reason(s) behind the output.
def check (n) : if n <=1: return True elif n % 2 == 0: return check (n/2) else: return check (n/1)
Figure out the problem with the following code that may occur when it is run.
def recur(p): if p == 0: print ("##") else: recur(p) p = p - 1
Write a method in Python to find and display the prime numbers from 2 to N. The value of N should be passed as an argument to the method.