斐波纳契数列(f(n)=f(n-1)+f(n-2))问题

\because f(n)=1\cdot f(n-1)+1\cdot f(n-2)

\begin{bmatrix} 1 &1 \\ 1& 0 \end{bmatrix}^{n-2}

package org.nxt.algorithm.series;

import java.math.BigInteger;

/**
 * fibonacci series
 * @author nanxiaotao
 *
 */
public class FibonacciSeries {
	
	private static BigInteger[][] matrix(BigInteger[][] arrLeft, BigInteger[][] arrRight){
	        BigInteger result[][] = {{new BigInteger("0"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("0")}};
	        for (int i = 0; i <= 1; i++){
	            for (int j = 0; j <= 1; j++){
	                result[i][j] =  arrLeft[i][0].multiply(arrRight[0][j]).add(arrLeft[i][1].multiply(arrRight[1][j]));
	            }
	        }
	        return result;
	    }
	 
	 
	 
	private static BigInteger[][] square(BigInteger [][] arrIn){
	        BigInteger result[][] = {{new BigInteger("0"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("0")}};
	 
	        BigInteger [][] arrLeft = arrIn;
	        BigInteger [][] arrRight = arrIn;
	 
	        if (arrIn != null){
	            for (int i = 0; i <= 1; i++){
	                for (int j = 0; j <= 1; j++){
	                    result[i][j] =  arrLeft[i][0].multiply(arrRight[0][j]).add(arrLeft[i][1].multiply(arrRight[1][j]));
	                }
	            }
	        }
	        return result;
	}
	 
	 
	   private static BigInteger[][] matrixFast(BigInteger[][] arrIn, int n){
	        BigInteger result[][] = arrIn;
	        BigInteger tmp[][] = {{new BigInteger("1"),new BigInteger("0")},{new BigInteger("0"),new BigInteger("1")}};//初始值为单位阵
	        while (n != 0){
	            if ((n & 1) == 1){
	                tmp = matrix(tmp.clone(), result);
	                result = square(result.clone());
	                n = n >> 1;
	            }else {
	                result = square(result.clone());
	                n = n>>1;
	            }
	        }
	        return tmp;
	    }
	 
	   
	   public static BigInteger computeN(int n) {
		   BigInteger arrIn[][] = {{new BigInteger("1"),new BigInteger("1")},{new BigInteger("1"),new BigInteger("0")}};
	       BigInteger res[][] = matrixFast(arrIn, n);
	       return res[0][0];
	   }
	 
	    public static void main(String[] args) {
	        System.out.println(computeN(6));
	    }



}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值