Stone Division, Revisited

  • + 0 comments

    This problem permits a really short recursive solution.
    Generally I prefer non-recursive approaches, as recursion tends to be slow (even with memo) and recursion depth limits may apply. However recursive solutions give more concise and elegant code.

    Python3:

    from functools import cache
    def stoneDivision(n, s):
        @cache
        def val(x):
            divs = [i for i in s if x%i == 0 and i!=x]
            return max(1 + val(i) * x//i for i in divs) if divs else 0
        return val(n)