斐波那契数列很常见,实现的方法主要有递归,for,栈等,下面给出代码
import java.math.BigInteger;
import java.util.Scanner;
import java.util.Stack; public class NFactorial {
public static void main(String[] args) {
System.out.println("请输入一个数:");
Scanner sc= new Scanner(System.in);
int q =sc.nextInt(); System.out.println("递归结果:"+factorial(q));
System.out.println("5的递归结果:"+factorial(new BigInteger("5")));
System.out.println("栈运算结果:"+factorial_stack(q));
System.out.println("for运算结果:"+factorial_for(q));
}
/*
* 用递归实现
* */
private static int factorial(int n){
if(n==0){
return 0;
}
if(n==1){
return 1;
}
else{
int temp =n*factorial(n-1); return temp;
}
} private static BigInteger factorial(BigInteger n){
if(n.compareTo(BigInteger.ONE)==-1){
return BigInteger.ZERO;
}
if(n.compareTo(BigInteger.ONE)==0){
return BigInteger.ONE;
}
else{
BigInteger temp =n.multiply(factorial(n.subtract(BigInteger.ONE)));
return temp;
}
} /*
* 用栈实现
* */
private static BigInteger factorial_stack(int n){
Stack stk=new Stack();
BigInteger num=BigInteger.ONE;
for(int i=1;i<=n;i++){
stk.push(i);
}
while (stk.size()>0){
BigInteger bign=new BigInteger(stk.pop().toString());
num=num.multiply(bign);
}
return num;
} /*
* 用for实现
* */
private static BigInteger factorial_for(int n){
BigInteger num=BigInteger.ONE;
for(int i=1;i<=n;i++){
BigInteger bign = new BigInteger(String.valueOf(i));
num=num.multiply(bign);
}
return num;
} }