Advertisement
thieumao

Do you know Fibonacci?

Jun 23rd, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. package fibonacci;
  2.  
  3. import java.util.HashMap;
  4. import java.math.BigInteger;
  5.  
  6. /*
  7. Do you know Fibonacci?
  8. Flag{last 11617 digits of Fibonacci(336129) module 12345678987654321}
  9. */
  10.  
  11. public class Fibonacci {
  12.  
  13.     private static HashMap<BigInteger, BigInteger> cache = new HashMap<BigInteger, BigInteger>();
  14.     private static BigInteger ONE = BigInteger.ONE;
  15.     private static BigInteger ZERO = BigInteger.ZERO;
  16.    
  17.     public static void main(String[] args) {
  18.         BigInteger n = new BigInteger("336129");
  19.         BigInteger fn = fibonacci(n);
  20.         BigInteger ten = new BigInteger("10");
  21.         BigInteger tenPow11617 = ten.pow(11617);
  22.         BigInteger last11617 = fn.mod(tenPow11617);
  23.         BigInteger mod = new BigInteger("123456789");
  24.         BigInteger result = last11617.mod(mod);
  25.         System.out.println("Result = " + result);
  26.     }
  27.  
  28.     // method tim so fibonacci thu n
  29.     public static BigInteger fibonacci(BigInteger n) {
  30.         if (n.equals(ZERO)) {
  31.             return ZERO;
  32.         }
  33.         if (n.equals(ONE)) {
  34.             return ONE;
  35.         }
  36.         if (cache.containsKey(n)) {
  37.             return cache.get(n);
  38.         }
  39.         if (n.testBit(0)) {
  40.             BigInteger n2 = n.shiftRight(1);
  41.             BigInteger n3 = n2.add(ONE);
  42.             BigInteger result = fibonacci(n2).multiply(fibonacci(n2)).add(fibonacci(n3).multiply(fibonacci(n3)));
  43.             cache.put(n, result);
  44.             return result;
  45.         } else {
  46.             BigInteger n2 = n.shiftRight(1);
  47.             BigInteger n3 = n2.subtract(ONE);
  48.             BigInteger result = fibonacci(n2).multiply(fibonacci(n2).add(fibonacci(n3).add(fibonacci(n3))));
  49.             cache.put(n, result);
  50.             return result;
  51.         }
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement