4. 求fibonacci数列第100项的值。fibonacci数列的第一项的值为1,第二项的值也为1,第三项以后的
值为其前两项的和。要求使用循环和递归的方法来实现。
循环实现:
static public void loop(){
BigInteger temp1 = new BigInteger("1");
BigInteger temp2 = new BigInteger("1");
for(int i=1;i<50;i++){
temp1 = temp1.add(temp2);
temp2 = temp1.add(temp2);
}
System.out.println(temp2);
}
递归实现:
static public void recursion(BigInteger num1,BigInteger num2,int count){
count++;
if(count != 50){
recursion(num1.add(num2),num1.add(num2).add(num2),count);
}else{
System.out.println(num2);
}
}
主函数调用:
public class Fibonacci {
static public void loop(){
***
}
static public void recursion(BigInteger num1,BigInteger num2,int count){
***
}
static public void main(String args[]){
BigInteger num1 = new BigInteger("1");
BigInteger num2 = new BigInteger("1");
int count= 0;
loop();
recursion(num1,num2,0);
}
}
问题求fibonacci数列第100项的值,在实现过程中我们通过初步估计使用int型数据类型一定是无法正确表示最终的结果的。所以我们使用Java类库为我们提供的BigInteger类型。至于BigInteger的具体使用,读者可以自行查找相关资料。
本博由大连理工大学软件学院优快云高校俱乐部原创,如需转载请注明。
欢迎广大读者关注大连理工大学软件学院优快云高校俱乐部,
大连理工大学软件学院优快云高校俱乐部隶属于大连理工大学软件学院OurEDA创新实验室,
OurEDA创新实验室目前暂分为移动创新实践部和嵌入式创新实践部,欢迎对创新实践感兴趣的同学加入。
OurEDA创新实验室主页:www.OurEDA.cn