fork download
  1. nthPartition <- function(m, n)
  2. {
  3. A <- matrix(0, m, m)
  4. A[1, 1:min(m, 5)] <- 1
  5. if (m > 1) for (i in 2:m) for (j in 1:5) A[i, 0:-j] <- A[i, 0:-j] + A[i - 1, 0:(m - j)]
  6.  
  7. for (L in 1:m) {
  8. if (n <= A[L, m]) break
  9. ifelse(L < m, n <- n - A[L, m], return(0))
  10. }
  11.  
  12. a <- integer(L)
  13. for (i in 1:L) {
  14. for (j in 1:5) {
  15. if (i < L) {
  16. if (n <= A[L - i, m - j]) break
  17. n <- n - A[L - i, m - j]
  18. } else {
  19. if (j == m) break
  20. }
  21. }
  22.  
  23. a[i] <- j
  24. m <- m - j
  25. }
  26.  
  27. paste(a, collapse = "")
  28. }
  29.  
  30. Q <- list(
  31. c(2, 1), c(2, 2), c(2, 3),
  32. c(20, 1), c(20, 2), c(20, 3), c(20, 400096), c(20, 400097),
  33. c(32, 1), c(32, 2), c(32, 3), c(32, 1000), c(32, 1000000), c(32, 1000000000), c(32, 1333610936), c(32, 1333610937)
  34. )
  35.  
  36. for (q in Q) cat(sprintf("(%d, %d) → %s\n", q[1], q[2], nthPartition(q[1], q[2])))
Success #stdin #stdout 0.35s 44236KB
stdin
Standard input is empty
stdout
(2, 1) → 2
(2, 2) → 11
(2, 3) → 0
(20, 1) → 5555
(20, 2) → 14555
(20, 3) → 15455
(20, 400096) → 11111111111111111111
(20, 400097) → 0
(32, 1) → 2555555
(32, 2) → 3455555
(32, 3) → 3545555
(32, 1000) → 34355354
(32, 1000000) → 11532334334
(32, 1000000000) → 2141111311212411131
(32, 1333610936) → 11111111111111111111111111111111
(32, 1333610937) → 0