招银笔试:100年后有多少只母牛
题目描述
假设每只母牛出生后,次年后的每一年年初会生下两只母牛,并且随着年份的增加
每年成倍的死亡,第一年死1*2,第二年2*2,第三年3*2
假设第一年年初有10投母牛,第二年后有28头,问100年后有多少只母牛
思路:
核心就是一句话:假设今年的母牛有n头,那么下一年有n*3 - 2 * year头。其中year表示第几年。
注意,这里用了Java的BigInteger,因为需要做大数处理。
递归写法:
import java.math.BigInteger;
public class Cow {
static final BigInteger a = new BigInteger("3");
static BigInteger getCount(int n, int year, BigInteger num) {
if(year <= n) {
num = num.multiply(a);
BigInteger b = new BigInteger(String.valueOf(((year-1) << 1)));
num = num.subtract(b);
return getCount(n, ++year, num);
}
return num;
}
public static void main(String[] args) {
BigInteger result = getCount(100, 2, new BigInteger("10"));
System.out.println(result);
}
}
非递归写法
import java.math.BigInteger;
public class Cow {
static BigInteger num = new BigInteger("10");
static final BigInteger a = new BigInteger("3");
static void solution() {
BigInteger n = num;
num = num.multiply(a);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 10;
int year = 2;
while(year <= 100) {
System.out.print("第" + year + "年");
solution();
BigInteger b = new BigInteger(String.valueOf(((year-1) << 1)));
num = num.subtract(b);
System.out.println("有"+num+"头");
year++;
}
}
}
运行结果如下: