Advertisement
Guest User

Analysis of an obfuscated fibonacci function

a guest
Feb 22nd, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. De-uglify
  2.  
  3. def f(n):
  4. a = 4 << n*(3+n)
  5. b = (4 << 2*n) - (2 << n) - 1
  6. c = ~-(2 << n)
  7. return (a // b) & c
  8.  
  9. ~-(2 << n) = 2**(n+1) - 1, so the & c is doing mod 2**(n+1).
  10.  
  11. Rewrite the shifts with exponents
  12.  
  13. def f(n):
  14. a = 4 * 2**(n*(3+n))
  15. b = 4 * 2**(2*n) - 2**(n+1) - 1
  16. return (a // b) % 2**(n+1)
  17.  
  18. Think a while and realize that b = 2**(2n+2)) - 2**(n+1) - 1 is p**2 - p - 1 if
  19. you set p = 2**(n+1), which sets off the Fibonacci-identity detector :) Rewrite
  20.  
  21. def f(n):
  22. p = 2**(n+1)
  23. a = p**(n+2)
  24. b = p**2 - p - 1
  25. return (a // b) % p
  26.  
  27. Look on wikipedia and see s(1/X) = X/(X**2 - X - 1) is the generating function
  28. for Fib, so a/b is p**(n+1) s(1/p), so f(n) is doing
  29.  
  30. floor( p**(n+1) (\sum_k Fib(k)/p^k) ) % p
  31.  
  32. Divide the sum into three parts: k < n+1, k = n+1, k > n+1
  33.  
  34. \sum_{k<n+1} Fib(k) p**(n+1-k) +
  35. Fib(n+1) +
  36. \sum_{k>n+1} Fib(k) p**(n+1-k)
  37.  
  38. So probably the mod is killing the first sum, which is big, and the floor is
  39. killing the last sum, which is small, leaving just Fib(n+1).
  40.  
  41. All the terms in the first sum are divisible by p, so the mod does kill it.
  42.  
  43. Since Fib(k) < 2**k, the middle term Fib(k+1) < p, so it is unchanged by the
  44. mod.
  45.  
  46. But showing that the last sum is < 1 is huge pain >:( Both the easy bounds
  47. Fib(k) < 2**k and Fib(k) < 2**(k-1) + 1/2 are too coarse! Using Fib(k) < (phi**k
  48. + 1)/2 will, after an annoying calculation and special casing the first three or
  49. so values of n, in the end give a good enough bound though, so the floor wipes
  50. out that sum leaving finally just
  51.  
  52. f(n) = Fib(n+1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement