求解斐波那契数列第100位(Java BigInteger版本)

求解斐波那契数列第100项

方案1(递归版本):

package JiaNan;
import java.math.BigInteger;
import java.util.*;

public class Fab100
{
	static Map map = new HashMap();
	static BigInteger f(int n)
	{
		if(map.get(n)!=null) return (BigInteger)map.get(n);
		BigInteger x = f(n-1).add(f(n-2));
		map.put(n,x);
		return x;
	}
	
	public static void main(String[] args)
	{
		Scanner cin = new Scanner(System.in);
		int m;
		while((m = cin.nextInt()) != 0)
		{
			map.put(1,BigInteger.ONE);
			map.put(2,BigInteger.ONE);
			System.out.println(f(m));
		}
	}
}

/*
100
354224848179261915075
*/

 方案2(非递归版本,即自底向上计算求解):

package JiaNan;
import java.math.BigInteger;
import java.util.*;
public class Fab100
{
	public static BigInteger fab(int n)
	{
		if(n==1 || n==2)
			return BigInteger.ONE;
		BigInteger a = BigInteger.ONE;
		BigInteger b = BigInteger.ONE;
		BigInteger sum = a.add(b);
		for(int i = 3;i < n;i++)
		{
			a = b;
			b = sum;
			sum = a.add(b);
		}
		return sum;
	}
	public static void main(String[] args)
	{
		Scanner cin = new Scanner(System.in);
		int n=cin.nextInt();
	    System.out.println(fab(n));
	}
}

/*
100
354224848179261915075
*/
 

 

你可能感兴趣的:(求解斐波那契数列第100位(Java BigInteger版本))