The number n! is defined as n × ( n – 1 ) × ( n – 2 ) × … × 2 × 1 .
(a) Can you write up a recursive method to calculate the value of n! ?
(b) You are given a function called print( n ) which shows the value of n on the screen. Using your idea in (a) above, can you write up a recursive method to print numbers from n to 0 on the screen?
Follow-up:
(a) The number n! is defined as n × ( n – 1 ) × ( n – 2 ) × … × 2 × 1 .
We can express its computation as a recursive method below. Assume n > 1 .
Calculate_Factorial(n)
- Is n = 1?
- If yes, then answer is: 1
- If no, then answer is: n x Calculate_Factorial(n-1)
(b) Using an idea similar to the above, we can solve the “printing” problem as follows. Assume n>0 .
Show_n_downto_0(n)
- print(n)
- Is n = 0?
- If yes, then we are done
- If no, then do: Show_n_downto_0(n-1)
We observe that
Can you write up a recursive method to calculate the value?
Follow-up:
We can express this computation as a recursive method below.
Calculate_Power(a, n)
- Is n = 1?
- If yes, then answer is: a
- If no, then:
- b = Calculate_Power(a, n/2)
- answer is then: b x b
No comments:
Post a Comment