首页 > 试题广场 >

小东分苹果

[编程题]小东分苹果
  • 热度指数:13111 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

果园里有一堆苹果,一共n头(n大于1小于8)熊来分,第一头为小东,它把苹果均分n份后,多出了一个,它扔掉了这一个,拿走了自己的一份苹果,接着第二头熊重复这一过程,即先均分n份,扔掉一个然后拿走一份,以此类推直到最后一头熊都是这样(最后一头熊扔掉后可以拿走0个,也算是n份均分)。问最初这堆苹果最少有多少个?


输入描述:
给定一个整数n,表示熊的头数


输出描述:
返回最初的苹果数。保证有解。
示例1

输入

2

输出

3
import java.util.*;
public class Apples {
    public int getInitial(int n) {
        int init=0,k,i,next=0,result;
        while(true){
            k=init;
            for(i=1; i<n; i++){
                next = k*n+1;
                if(next%(n-1)==0){
                   k=next/(n-1); 
                }
                else{
                    init++;
                    break;
                }
            }
            if(i==n){
                result = k*n+1;
                break;
            }
        }
        return result;
    }
}
 init   is the apples the last bear got;
k   is the next bear got; 
i   is the number of bear i=1 means the last bear;
next   is when the # i   bear  come, how many  apples in the heap.
发表于 2016-07-21 20:01:26 回复(0)