|
U
Pro15. Recursive Sum and Factorial
Easy
Problem Description
Given a non-negative integer N, compute two recursive mathematical quantities:
- 1.The recursive sum S(N)=1+2+⋯+N (with S(0)=0).
- 2.The factorial F(N)=N!=N×(N−1)×⋯×1 (with F(0)=1).
Input Format
A single line containing an integer N (0≤N≤20).
Output Format
Print two space-separated integers: S(N) followed by F(N).
Example 1:
Input:
5
Output:
15 120
Explanation: Sum = 1 + 2 + 3 + 4 + 5 = 15. Factorial = 5! = 120.
Example 2:
Input:
0
Output:
0 1
Explanation: Base cases: sum of 0 numbers is 0, and 0! = 1.
Example 3:
Input:
3
Output:
6 6
Explanation: Sum = 1 + 2 + 3 = 6. Factorial = 3! = 6.
Constraints:
0 <= N <= 20Time complexity target: O(N)Auxiliary space target: O(N) call stack
Follow up:How can tail-call optimization transform these recursive functions to execute in O(1) stack space?
1,180 Online
Code
|Loading Code Editor...
SavedLn 1, Col 1
input =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit