MOD = 10**9 + 7 def subtract_one(s): s_list = list(s) i = len(s_list) - 1 while i >= 0 and s_list[i] == '0': s_list[i] = '9' i -= 1 if i < 0: return '0' s_list[i] = str(int(s_list[i]) - 1) if s_list[0] == '0' and len(s_list) > 1: return ''.join(s_list[1:]) return ''.join(s_list) def compute(X, P): if X == '0': return 0 digits = list(map(int, X)) n = len(digits) # Initialize DP table: [tight][leading_zero][has_three][mod3][mod_p] current_dp = [[[[[0] * P for _ in range(3)] for __ in range(2)] for ___ in range(2)] for ____ in range(2)] current_dp[1][1][0][0][0] = 1 # Initial state for i in range(n): next_dp = [[[[[0] * P for _ in range(3)] for __ in range(2)] for ___ in range(2)] for ____ in range(2)] for tight in [0, 1]: for leading_zero in [0, 1]: for has_three in [0, 1]: for mod3 in [0, 1, 2]: for mod_p in range(P): cnt = current_dp[tight][leading_zero][has_three][mod3][mod_p] if cnt == 0: continue upper = digits[i] if tight else 9 for d in range(0, upper + 1): new_tight = 1 if (tight and d == upper) else 0 new_leading_zero = 1 if (leading_zero and d == 0) else 0 new_has_three = 1 if (has_three or (d == 3)) else 0 if leading_zero: if d == 0: new_mod3_ = 0 new_mod_p_ = 0 else: new_mod3_ = d % 3 new_mod_p_ = d % P else: new_mod3_ = (mod3 * 10 + d) % 3 new_mod_p_ = (mod_p * 10 + d) % P next_dp[new_tight][new_leading_zero][new_has_three][new_mod3_][new_mod_p_] = ( next_dp[new_tight][new_leading_zero][new_has_three][new_mod3_][new_mod_p_] + cnt ) % MOD current_dp = next_dp result = 0 for tight in [0, 1]: for leading_zero in [0, 1]: for has_three in [0, 1]: for mod3 in [0, 1, 2]: for mod_p in range(P): if leading_zero: continue cond1 = (mod3 == 0) or (has_three == 1) cond2 = (mod_p != 0) if cond1 and cond2: result = (result + current_dp[tight][leading_zero][has_three][mod3][mod_p]) % MOD return result def main(): import sys input = sys.stdin.read().split() A = input[0] B = input[1] P = int(input[2]) A_minus_1 = subtract_one(A) ans = (compute(B, P) - compute(A_minus_1, P)) % MOD print(ans) if __name__ == "__main__": main()