modular_fibonacci.jl 679 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/julia
  2. # Date: 21 August 2016
  3. # https://github.com/trizen
  4. # An efficient algorithm for computing large Fibonacci numbers, modulus some n.
  5. # Algorithm from: https://codeforces.com/blog/entry/14516
  6. function fibmod(n::Int64, mod::Int64)
  7. n <= 1 && return n
  8. cache = Dict{Int64, Int64}()
  9. function f(n::Int64)
  10. n <= 1 && return 1
  11. haskey(cache, n) && return cache[n]
  12. k = div(n, 2)
  13. cache[n] =
  14. if n % 2 == 0
  15. (f(k) * f(k ) + f(k-1) * f(k-1)) % mod
  16. else
  17. (f(k) * f(k+1) + f(k-1) * f(k )) % mod
  18. end
  19. end
  20. f(n-1)
  21. end
  22. println(fibmod(1000, 10^4))