Advertisement
iamcreasy

fibonacci series, iterative version, BigInteger in Java

Jun 15th, 2016
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. import java.math.BigInteger;
  2.  
  3. /**
  4.  * Created by iamcreasy on 6/15/2016.
  5.  */
  6. public class Test2 {
  7.     public static void main(String[] args) {
  8.         long currentTime = System.currentTimeMillis();
  9.  
  10.         System.out.println(fib(1000));
  11.  
  12.         System.out.println("\nfib function took " + (System.currentTimeMillis() - currentTime) + " miliseconds");
  13.     }
  14.  
  15.     static BigInteger fib(long nth){
  16.         nth = nth - 1;
  17.         long count = 0;
  18.         BigInteger first = BigInteger.ZERO;
  19.         BigInteger second = BigInteger.ONE;
  20.  
  21.         BigInteger third = null;
  22.         while(count < nth){
  23.             third = new BigInteger(first.add(second).toString());
  24.             first = new BigInteger(second.toString());
  25.             second = new BigInteger(third.toString());
  26.             count++;
  27.         }
  28.  
  29.         return third;
  30.     }
  31. }
  32.  
  33. // Output :
  34. // 4346655768693745643568852767504062580256466051737178040248172908953655541794905189040387984007925516929592259308032
  35. // 2634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
  36. //
  37. // fib function took 41 miliseconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement