The Great Trickster

Time limit1sMemory limit128 MB

Summary
Count integers from 0 to n whose base-k and base(-k) representations are identical, with n up to 10^15 and k up to 1000.
Level

Hard8 of 10

Topics
Math, Number theory, Dynamic programming, Combinatorics
Solved
No attempts yet

Problem

Hard as it is to believe, Sanggeun went to the Moon over the winter break. Back at school, he told his friends all about meeting the Selenites — the people of the Moon.

Mostly he explained the number system used on the Moon: the Selenites write numbers in a negative base.

Negative bases are hard for people to grasp. So during his trip, Sanggeun memorized every number between 00 and nn (inclusive) whose representation in base kk is identical to its representation in base −k-k. Write a program that counts how many numbers he memorized.

The base-kk representation of xx is a sequence a0,a1,…,apa_0, a_1, \ldots, a_p satisfying 0≤ai<∣k∣0 \le a_i < |k| and ∑i=0paiki=x\sum_{i=0}^{p} a_i k^i = x.

Input

The first line contains two integers nn and kk (1≤n≤10151 \le n \le 10^{15}, 2≤k≤10002 \le k \le 1000).

Output

Print the number of integers between 00 and nn whose base-kk and base-(−k)(-k) representations are the same.

Note

For n=21n = 21, k=3k = 3, the memorized numbers are 0,1,2,9,10,11,18,19,200, 1, 2, 9, 10, 11, 18, 19, 20. For example, 19=2013=201−319 = 201_3 = 201_{-3}, so its two representations match, whereas 7=213=111−37 = 21_3 = 111_{-3}, so they do not.

For n=21n = 21, k=2k = 2, the memorized numbers are 0,1,4,5,16,17,20,210, 1, 4, 5, 16, 17, 20, 21.

Examples2

  1. Example 1

    Input
    21 3
    
    Expected output
    9
    
  2. Example 2

    Input
    21 2
    
    Expected output
    8