Tutorial 9 Worksheet
Tutorial 9 Worksheet
Tutorial objectives:
• To have a better understanding of Python function
• To understand the way of using recursion to solve a problem
• Deadline: 23:59 Apr 23, 2024
Tase Case 2
Input:
5
Output:
8
Tase Case 3
Input:
10
Output:
3840
Tase Case 4
Input:
20
Output:
3715891200
Tase Case 5
Input:
15
Output:
645120
1 IN 4
Exercise 9.2 Multiply two number
Implement a recursive function multiply(a, b) to calculate the value of a*b without using the *
operator.
• a, b >= 0 and min(a, b) <= 1000
• Must use recursive function to solve this problem
• Don’t use the * operator in your implementation
• Try to avoid some unnecessary computation in your implementation by the if-else statement.
Otherwise, it may cause runtime errors for some of the cases
• Hint: a * b = a + a * (b - 1) or b + b * (a - 1); Try to use this to decrease the input size of your
function
a = int(input())
b = int(input())
print(multiply(a, b))
Test Case 2
Input:
50
100
Output:
5000
Test Case 3
Input:
1
1000
Output:
1000
Test Case 4
Input:
1000
1
Output:
1000
2 IN 4
Exercise 9.3 Special sequence
There is a number sequence: 2, 1, 3, 2, 3, 6, 6, 18, 36, 108, 648, 3888, 69984 …
Try to implement the func(n) to calculate the nth value of this number sequence.
• n >= 0,
• Must use the recursive function to solve this problem
• Hint: In this number sequence, the first 3 numbers (2, 1, 3) are fixed; The fourth number is
calculated as the product of the first two numbers. The rest of the numbers in the following
sequence will follow the same pattern.
n = int(input())
print(func(n))
Test case 2
Input:
20
Output:
5798976440091547641555385157483998407888470016
Test case 3
Input:
15
Output:
176319369216
3 IN 4
Exercise 9.4 Digit calculator
Try to implement func(n, digit) to calculate the times that the digit (0 <= digit <=9) shown in the
interval [1, n].
n = int(input())
digit = int(input())
print(func(n, digit))
Test case 2
Input:
22
2
Output:
6
Test case 3
Input:
20
1
Output:
12
4 IN 4