【题面】
猴子第一天摘下若干桃子,当即吃了一半,还不过瘾,又多吃了一个。第二天早上又将剩下的桃子吃掉的一半,又多吃了一个。以后每天早上都吃掉了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘多少桃子。
很明显的一道递推题。又 f[n] = f[n - 1] / 2 - 1 可知 f[n - 1] = f[n] * 2 + 2 即 f[n] = f[n + 1] * 2 + 2,递推式就出来了。
代码也很短
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 using namespace std; 7 void solve(int n) 8 { 9 int ans = 1; //第一天有一个 10 for(int i = 2; i <= n; ++i) 11 ans = ans * 2 + 2; 12 printf("%d ", ans); 13 return; 14 } 15 int main() 16 { 17 solve(10); 18 return 0; 19 }
输出:1534
当然,递归也没问题
1 #include<cstdio> 2 #include<iostream> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 using namespace std; 7 int solve(int x) 8 { 9 if(x == 1) return 1; 10 return (solve(x - 1) * 2 + 2); 11 } 12 int main() 13 { 14 printf("%d ", solve(10)); 15 return 0; 16 }