猴子分桃子

来源:互联网 发布:登录阿里云邮箱登陆 编辑:程序博客网 时间:2024/04/28 03:08

题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个,它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子?

自己的代码:

package com.ytzl.test;


public class Monkey {
public static void main(String[] args) {
int i=5;
/*for (int i = 1; i < 100000000; i++)*/while(true) {
i++;
if ((i - 1) % 5 == 0) {
int j = 4 * (i - 1) / 5;
if ((j - 1) % 5 == 0 ) {
int k = 4 * (j - 1) / 5;
if ((k - 1) % 5 == 0 ) {
int l = 4 * (k - 1) / 5;
if ((l - 1) % 5 == 0 ) {
int m = 4 * (l - 1) / 5;
if ((m - 1) % 5 == 0 ) {
int n = 4 * (m - 1) / 5;
System.out.println(i);
break;
}
}
}
}
}
}
}
}

结果为3121.

经过了5层if判断及赋值,未能把这几次总结成循环,嵌套次数较多易出错。

package com.ytzl.test;
import java.util.Scanner;
public class Monkey2 {
public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.println("输入猴子的数目");
       int number = scanner.nextInt(); //输入猴子的数目
       int i = 0, m = 1, x = 1;
       while (true) {
           m = x;
           for (i = 0; i < number; i++) {
               if ((m - 1) % number == 0) {
                   m = (m - 1) / number * 4;
               } else {
                   break;
               }
           }
           if (i == number && m > 0) {
               break;
           }
           x++;
       }
       System.out.println(x);
}
}

可以算除了5只以外的多只猴子分桃子的问题,且循环赋值,代码较简洁。