1+ import java .io .BufferedReader ;
2+ import java .io .IOException ;
3+ import java .io .InputStream ;
4+ import java .io .InputStreamReader ;
5+ import java .util .StringTokenizer ;
6+
7+ public class NthFibonacci {
8+ public static void main (String [] args ) throws IOException {
9+ Reader .init (System .in );
10+ System .out .println ("Enter the number of term to be printed:" );
11+ long n = Reader .nextLong ();
12+ System .out .println (smartfib (n )[1 ][0 ]);
13+ }
14+
15+ public static long [][] smartfib (long n ){
16+ long a [][]=new long [2 ][2 ];
17+ a [0 ]= new long []{1 , 1 };
18+ a [1 ]= new long []{1 ,0 };
19+ if (n ==0 ){
20+ a [1 ][0 ]=0 ;
21+ return a ;
22+ }
23+ if (n ==1 ){
24+ return a ;
25+ }
26+ if (n %2 ==1 ){
27+ return product (square (smartfib (((n -1 )/2 ))),a );
28+ }
29+ return square (smartfib ((n /2 )));
30+ }
31+ public static long [][] square (long a [][]){
32+ long b [][]=new long [2 ][2 ];
33+ for (int i =0 ;i <2 ;i ++){
34+ for (int j =0 ;j <2 ;j ++){
35+ long sum =0 ;
36+ for (int k =0 ;k <2 ;k ++){
37+ sum +=(a [i ][k ]*a [k ][j ]);
38+ }
39+ b [i ][j ]=sum ;
40+ }
41+ }
42+ return b ;
43+ }
44+ public static long [][] product (long a [][],long b [][]){
45+ long c [][]=new long [2 ][2 ];
46+ for (int i =0 ;i <2 ;i ++){
47+ for (int j =0 ;j <2 ;j ++){
48+ long sum =0 ;
49+ for (int k =0 ;k <2 ;k ++){
50+ sum +=(a [i ][k ]*b [k ][j ]);
51+ }
52+ c [i ][j ]=sum ;
53+ }
54+ }
55+ return c ;
56+ }
57+ }
58+
59+ class Reader {
60+ static BufferedReader reader ;
61+ static StringTokenizer tokenizer ;
62+
63+ static void init (InputStream input ) {
64+ reader = new BufferedReader (
65+ new InputStreamReader (input ) );
66+ tokenizer = new StringTokenizer ("" );
67+ }
68+
69+ static String next () throws IOException {
70+ while ( ! tokenizer .hasMoreTokens () ) {
71+ tokenizer = new StringTokenizer (
72+ reader .readLine () );
73+ }
74+ return tokenizer .nextToken ();
75+ }
76+
77+ static int nextInt () throws IOException {
78+ return Integer .parseInt ( next () );
79+ }
80+
81+ static double nextDouble () throws IOException {
82+ return Double .parseDouble ( next () );
83+ }
84+ static long nextLong () throws IOException {
85+ return Long .parseLong ( next () );
86+ }
87+ }
0 commit comments