bernoulli_numbers_seidel.jl 835 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/julia
  2. # Trizen
  3. # 14 October 2016
  4. # https://github.com/trizen
  5. # Algorithm from:
  6. # https://oeis.org/wiki/User:Peter_Luschny/ComputationAndAsymptoticsOfBernoulliNumbers#Seidel
  7. using Printf
  8. const BONE = big"1"
  9. function bernoulli_seidel(n)
  10. n == 0 && return 1
  11. n == 1 && return 1//2
  12. isodd(n) && return 0
  13. D = append!([0, BONE], [0 for i in 1:(n/2-1)])
  14. h = 2
  15. b = false
  16. for i in 1:n
  17. if b
  18. for k in 2:h-1
  19. D[k] += D[k-1]
  20. end
  21. else
  22. w = h-1
  23. h += 1
  24. while w > 1
  25. D[w] += D[w+1]
  26. w -= 1
  27. end
  28. end
  29. b = !b
  30. end
  31. D[h-1] // ((BONE << (n+1)) - 2) * ((n % 4) == 0 ? -1 : 1)
  32. end
  33. for i in 0:50
  34. @printf("B%-3d = %s\n", 2*i, bernoulli_seidel(2*i))
  35. end