Tutorial 5 Worksheet: COMP1117A Computer Programming I 2018-2019
Tutorial 5 Worksheet: COMP1117A Computer Programming I 2018-2019
Tutorial objectives:
- Midterm solutions of Question A and B
- To practice the use of recursive functions in Python.
Tutorial 5 Exercises Deadline: Nov 8, 2018 14:20
1. Midterm solutions
Demo: Question A
Write a complete Python program that reads an integer, then multiply it by 2, and print the
sum of the digits in the result. For example, if the input is 123, then your program should
output 12 because 123 × 2 = 246 and 2 + 4 + 6 = 12 .
Note: You may assume that the input contains only the digits ‘0’, ‘1’, ‘2’, …, ‘9’.
n = int(input())
n = n * 2
- Then we should find out the digits one by one in the number.
sum = n % 10
while n >= 10:
n = n // 10
sum = sum + n % 10
print(sum)
Demo: Question B
A positive integer is interesting if it is the sum of two prime numbers. Write a complete Python
program that inputs a positive integer m, and print the character ‘Y’ if m is interesting, and
print the character ‘N’ otherwise. Again, you may assume the input contains only digits.
Note: 1 is not a prime number, and any integer greater than 1 is a prime number if it is only
divisible by 1 and itself.
m = int(input())
def prime(n):
if n == 1:
return False
flag = False
- Then check the number one by one to see any pairs of numbers could give the sum as the
input number and both of them are prime.
if flag:
print('Y')
else:
print('N')
Exercise 5.1 Combination
In mathematics, “combinations refer to the combination of n things taken k at a time without
repetition”. [1] There is a recursive formula related to combinations:
nCr = n − 1Cr − 1 + n − 1Cr
And nC0 = nCn = 1 , nCk = 0 if k > n .
Write a Python program to calculate the value of nCr of the given n and r by using this
recursive function.
Remarks: For more information about Combination, you may visit [1]
[1]: https://en.wikipedia.org/wiki/Combination
6 20
3
8 8
1
Write a program to calculate the factorial of a given number n by using the recursive function.
n! = n × (n − 1)!
And 0! = 1 .
Remarks: For more information about Factorial, you may visit this website
https://en.wikipedia.org/wiki/Factorial
1 1
5 120
Exercise 5.3 Ackermann function
Remarks: For more information about Ackermann function, you may visit this website
https://en.wikipedia.org/wiki/Ackermann_function
1 4
2
4 13
0