fork(6) download
import java.math.BigInteger;

public class Main {
	// матричное умножение двух матриц размера 2 на 2
	public static BigInteger[][] matrixMultiplication(BigInteger[][] a, BigInteger[][] b) {
		// [a00 * b00 + a01 * b10, a00 * b01 + a01 * b11]
		// [a10 * b00 + a11 * b10, a10 * b01 + a11 * b11]
		return new BigInteger[][]{
				{
						a[0][0].multiply(b[0][0]).add(a[0][1].multiply(b[1][0])),
						a[0][0].multiply(b[0][1]).add(a[0][1].multiply(b[1][1]))
				},
				{
						a[1][0].multiply(b[0][0]).add(a[1][1].multiply(b[1][0])),
						a[1][0].multiply(b[0][1]).add(a[1][1].multiply(b[1][1]))
				},
		};
	}

	// возведение матрицы размера 2 на 2 в степень n
	public static BigInteger[][] matrixPowerFast(BigInteger[][] a, int n) {
		if (n == 0) {
			// любая матрица в нулевой степени равна единичной матрице
			return new BigInteger[][]{
					{BigInteger.ONE, BigInteger.ZERO},
					{BigInteger.ZERO, BigInteger.ONE}
			};
		} else if (n % 2 == 0) {
			// a ^ (2k) = (a ^ 2) ^ k
			return matrixPowerFast(matrixMultiplication(a, a), n / 2);
		} else {
			// a ^ (2k + 1) = (a) * (a ^ 2k)
			return matrixMultiplication(matrixPowerFast(a, n - 1), a);
		}
	}

	// функция, возвращающая n-ое число Фибоначчи
	public static BigInteger fibonacci(int n) {
		if (n == 0) {
			return BigInteger.ZERO;
		}

		BigInteger[][] a = {
				{BigInteger.ONE, BigInteger.ONE},
				{BigInteger.ONE, BigInteger.ZERO}
		};
		BigInteger[][] powerOfA = matrixPowerFast(a, n - 1);
		// nthFibonacci = powerOfA[0][0] * F_1 + powerOfA[0][0] * F_0 = powerOfA[0][0] * 1 + powerOfA[0][0] * 0
		BigInteger nthFibonacci = powerOfA[0][0];
		return nthFibonacci;
	}

	public static void main(String[] args) {
		System.out.println(fibonacci(1024));
	}
}
Success #stdin #stdout 0.05s 4575232KB
stdin
Standard input is empty
stdout
4506699633677819813104383235728886049367860596218604830803023149600030645708721396248792609141030396244873266580345011219530209367425581019871067646094200262285202346655868899711089246778413354004103631553925405243