TD 2 Recursion
TD 2 Recursion
TD 02: Recursion
(
a if b = 0
gcd(a, b) =
gcd(b, a mod b) if b > 0
Exercise 4 Example:
Input: "aba"
1. Write a recursive function DecimalToOctal(n) The possible unique permutations are:
that converts a decimal number n to its octal
representation. The function should return an
aab, aba, baa
integer representing the octal equivalent of n.
2. Write a recursive function SumOfOctalDigits(n) Hint:
that computes the sum of the digits of the oc-
tal representation of n. Instead of directly • Sort the string before passing it to the recursive
computing the sum, this function should call function using qsort() from stdlib.h.
DecimalToOctal(n) to obtain the octal num-
ber and then recursively sum its digits. • Modify the recursive function to skip duplicate
characters when generating permutations.
3. Write a recursive function IsSumEven(n) that
determines whether the sum of the digits of the
octal representation of n is even or odd. Instead Exercise 6
of computing the sum directly, this function
should call SumOfOctalDigits(n) and return In an e-commerce system, there are two processes
true if the sum is even and false otherwise. that depend on each other and recursively call each
other in an alternating fashion. Consider two func-
Example: For n = (67)10 (decimal) tions, CheckOrder() and UpdateInventory(), as fol-
lows:
• Convert to octal using DecimalToOctal(67):
CheckOrder(orderID): This function checks if an or-
(67)10 = (103)8 der is valid. If the order ID is even, the order is con-
sidered valid. If the order ID is odd, the order is
• Compute the sum of the octal digits using considered invalid.
SumOfOctalDigits(67): UpdateInventory(orderID): This function updates
the inventory by decreasing it by 1 for each valid
1+0+3=4
order. After updating the inventory, it calls the
CheckOrder() function to check the validity of the
• Check if the sum is even using IsSumEven(67):
order again.
4 is even ⇒ true These two functions call each other recursively, alter-
nating between checking the order and updating the
inventory. The recursion continues until the order is
Exercise 5 processed or deemed invalid.
Using the recursive function Permutations(s) de-
fined in the previous exercise, write a new function (
UniquePermutations(s) that generates and displays valid order if order exists
CheckOrder(orderID) =
only the unique permutations of a given string s, even invalid order otherwise
if it contains duplicate characters.
To achieve this, you should use the C standard li-
brary function qsort() to sort the input string be- (
fore generating permutations, ensuring that duplicate U pdateInventory(orderID) = reduce stock if valid
permutations are not printed multiple times. alert if invalid