class FenwickTree: def __init__(self, size): self.n = size self.tree = [0] * (self.n + 1) # 1-based indexing def update(self, idx, delta): # Convert to 1-based index idx += 1 while idx <= self.n: self.tree[idx] += delta idx += idx & -idx def query(self, idx): # Sum from 0 to idx (0-based) idx += 1 res = 0 while idx > 0: res += self.tree[idx] idx -= idx & -idx return res def query_range(self, a, b): if a > b: return 0 return self.query(b) - (self.query(a - 1) if a > 0 else 0) def main(): import sys N, S = map(int, sys.stdin.readline().split()) # Precompute factorials up to S-1! max_fact = S factorial = [1] * (max_fact) for i in range(1, max_fact): factorial[i] = factorial[i-1] * i # Step 1: Generate permutation from N def get_permutation(n, s): perm = [] available = list(range(s)) for i in range(s): remaining = s - i - 1 fact = factorial[remaining] if remaining >=0 else 1 k = n // fact selected = available[k] perm.append(selected) del available[k] n = n % fact return perm P = get_permutation(N, S) # Step 2: Compute inverse permutation inv_P = [0] * S for i in range(S): inv_P[P[i]] = i # Step 3: Compute the index of inv_P ft = FenwickTree(S) for i in range(S): ft.update(i, 1) m = 0 for i in range(S): current = inv_P[i] remaining = S - i - 1 fact = factorial[remaining] if remaining >= 0 else 1 # Number of elements less than 'current' that are still available count = ft.query_range(0, current - 1) m += count * fact ft.update(current, -1) print(m) if __name__ == '__main__': main()