Implement the recursive function given by the following rules and print the last 3 digits:
F(x, y) = {
y + 1 when x = 0,
F(x - 1, 1) when x > 0 and y = 0,
F(x - 1, F(x, y - 1)) when x > 0 and y > 0
}
Example:
Input: x = 1, y = 100
Output: 102
Approach
C++
#include <bits/stdc++.h>using namespace std;int f[10001][10001];int recursiveFunction(int x, int y){if (f[x][y] != 0)return f[x][y];else{if (x == 0)f[x][y] = y + 1;else if (y == 0)f[x][y] = recursiveFunction(x - 1, 1);elsef[x][y] = recursiveFunction(x - 1,recursiveFunction(x, y - 1));return f[x][y];}}int main(){int x = 1, y = 100;int ans = recursiveFunction(x, y);if (ans < 1000)cout << ans << "\n";else{int cnt = 0;string str = "";while (cnt < 3){int rem = ans % 10;str += to_string(rem);ans = ans / 10;cnt++;}reverse(str.begin(), str.end());cout << str << "\n";}return 0;}
No comments:
Post a Comment