递归解决分鱼问题
#include <iostream> using namespace std; /*题目: A、B、C、D、E5个人在某天夜里合伙去捕鱼,到第二天凌晨时都疲惫不堪,于是各自找地方睡 觉。第二天,A第一个醒来,他将鱼分成5份,把多余的一条鱼扔掉,拿走自己的一份。B第二个醒 来,也将鱼分为5份,把多余的一条扔掉,拿走自己的一份。c、D、E依次醒来,也按同样的方法拿 鱼。问他们合伙至少捕了多少条鱼? */ /*分析 根据题意假设鱼的总数是x,那么第一次每人分到的鱼的数量可用(x一1)巧表示,余下的鱼数为4* (x-l)巧,将余下的数量重新赋值给x,依然调用(x一1)巧,如果连续5次x一1均能被5整除,则说明最初 的x值便是本题目的解。 */ int sub(int n) { if (n == 1) { static int i = 0; do { i++; } while (i % 5 != 0); return (i + 1); } else { int t; do { t = sub(n - 1); } while (t % 4 != 0); return (t / 4 * 5 + 1); } } int main() { int total; total = sub(5); // the total number of fish is 3121 cout << "the total number of fish is " << total; return 0; }