def last_remaining2(n: int, m: int) -> int:
    """
    n = 1: f(n, m) = 0
    n > 1: f(n, m) = (f(n-1, m) + m) % n
    """
    if n <= 0 or m <= 0:
        return -1
    last = 0
    for i in range(2, n+1):
        last = (last + m) % i
    return last