海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?
第一种方法:就只是简单的将这5次分的桃子列出,再定义一个值承接,非常简单明了
public class Main2 {
public static void main(String[] args) {
for (int i = 0;; i++) {
int tao1 = i;
if (tao1 % 5 == 1) {
int tao2 = (tao1 - 1) - (tao1 - 1) / 5;
if (tao2 % 5 == 1) {
int tao3 = (tao2 - 1) - (tao2 - 1) / 5;
if (tao3 % 5 == 1) {
int tao4 = (tao3 - 1) - (tao3 - 1) / 5;
if (tao4 % 5 == 1) {
int tao5 = (tao4 - 1) - (tao4 - 1) / 5;
if (tao5 % 5 == 1) {
System.out.println(tao1);
break;
}
}
}
}
}
}
}
}
第二种和第三种都用到了递归,代码更加简便,但是不太容易理解,也就是将第一种方法中重复的代码化简,只要找到桃子初始数量、猴子的数量、每次分过之后桃子的数量这三者的关系就能理解代码
public class Main2_1 {
public static void main(String[] args) {
System.out.println(show(0, 5, 0));
show(5, 0);
}
/**
* @param count 桃子的初始数量
* @param monkey 记录猴子的数量,
* @param taozi 记录每次分过之后桃子的数量
* @return
*/
// 第二种方法
public static int show(int count, int monkey, int taozi) {
if (monkey == 0) {
return count;
} else {
if (taozi % 5 == 1) {
//当猴子开始分桃子时,保证总数(count)不会变
return show(count, monkey - 1, (taozi - 1) - (taozi - 1) / 5);
} else {
//桃子不够猴子分,增加一个桃子的数量,桃子的数量和count是同步增加的
return show(count + 1, 5, count + 1);
}
}
}
/**
* @param monkey 猴子的数量
* @param taozi 记录每次分过之后的桃子数量
*/
/*
* 第二种和第三种方法类似,第二种中的count代表的意义相当于第三种中的i
* 规律相同
*/
//第三种方法
static int i = 0;//初始桃子数量
public static void show(int monkey, int taozi) {
if (monkey == 0) {
System.out.println(i);
return;
} else {
if (taozi % 5 == 1) {
//当猴子开始分桃子时,保证总数(i)不会变
show(monkey - 1, (taozi - 1) - (taozi - 1) / 5);
return;
} else {
//桃子不够猴子分,增加一个桃子的数量,桃子的数量和i是同步增加的
i++;
show(5, i);
return;
}
}
}
}

博客探讨了一道数学问题,五只猴子分桃子,每次分完后都会多一个,多的被扔掉并重新分配。文章通过三种方法解释解题过程,包括直接列出分桃子的过程、使用递归等,旨在找出海滩上原来最少有多少个桃子。
999

被折叠的 条评论
为什么被折叠?



