fork download
  1. library(gmp)
  2.  
  3. Solve <- function(p, n, s)
  4. {
  5. P <- p[-1] - p[1]
  6. g <- as.integer(gcdex(P[1], P[2]))
  7. a <- (s - n * p[1]) * g[-1] / g[1]
  8. b <- c(P[2], -P[1]) / g[1]
  9. if (any(a != floor(a))) return(cat("解なし\n\n"))
  10.  
  11. A <- c(a, sum(a))
  12. B <- c(b, sum(b))
  13. c <- -A / B
  14. d <- (n - A) / B
  15. tmin <- ceiling(max(pmin(c, d)))
  16. tmax <- floor(min(pmax(c, d)))
  17. if (tmin > tmax) return(cat("解なし\n\n"))
  18.  
  19. for (t in tmin:tmax) {
  20. m <- a + b * t
  21. m <- c(n - sum(m), m)
  22. cat(paste(sprintf("%d円×%d", p, m), collapse = " + "), " = ", s, "円\n", sep = "")
  23. }
  24. cat("\n")
  25. }
  26.  
  27. Solve(c(460, 580, 600), 10, 5360)
  28. Solve(c(460, 540, 580), 10, 5360)
  29. Solve(c(460, 520, 580), 10, 5360)
Success #stdin #stdout #stderr 0.32s 43984KB
stdin
Standard input is empty
stdout
460円×4 + 580円×4 + 600円×2 = 5360円

460円×3 + 540円×2 + 580円×5 = 5360円
460円×2 + 540円×5 + 580円×3 = 5360円
460円×1 + 540円×8 + 580円×1 = 5360円

解なし

stderr
Attaching package: ‘gmp’

The following objects are masked from ‘package:base’:

    %*%, apply, crossprod, matrix, tcrossprod