count_partitions_rec.jl 853 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/julia
  2. # Trizen
  3. # Date: 19 August 2016
  4. # https://github.com/trizen
  5. # Count the number of partitions of n, using a recursive relation.
  6. # See also: https://oeis.org/A000041
  7. # https://en.wikipedia.org/wiki/Partition_(number_theory)
  8. function partitions_count(n::Int64, cache::Dict{Int,Int})
  9. n <= 1 && return n
  10. if haskey(cache, n)
  11. return cache[n]
  12. end
  13. sum_1 = 0
  14. for i in 1:Int64(floor((sqrt(24*n + 1) + 1)/6))
  15. sum_1 += ((-1)^(i-1) * partitions_count(n - div(i*(3*i - 1), 2), cache))
  16. end
  17. sum_2 = 0
  18. for i in 1:Int64(ceil((sqrt(24*n + 1) - 7)/6))
  19. sum_2 += ((-1)^(i-1) * partitions_count(n - div((-i) * (-3*i - 1), 2), cache))
  20. end
  21. x = (sum_1 + sum_2)
  22. cache[n] = x
  23. x
  24. end
  25. println("P(200) = ", partitions_count(200+1, Dict{Int64, Int64}())) # 3972999029388