Number Transformation

Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer a. There’s only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer b. Petya decided to turn his number a into the number b consecutively performing the operations of the following two types:

  1. Subtract 1 from his number.
  2. Choose any integer x from 2 to k, inclusive. Then subtract number (a mod x) from his number a. Operation a mod x means taking the remainder from division of number a by number x.

Petya performs one operation per second. Each time he chooses an operation to perform during the current move, no matter what kind of operations he has performed by that moment. In particular, this implies that he can perform the same operation any number of times in a row.

Now he wonders in what minimum number of seconds he could transform his number a into number b. Please note that numbers x in the operations of the second type are selected anew each time, independently of each other.


The only line contains three integers ab (1 ≤ b ≤ a ≤ 1018) and k (2 ≤ k ≤ 15).

Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.


Print a single integer — the required minimum number of seconds needed to transform number a into number b.



10 1 4




6 3 10




1000000000000000000 1 3




In the first sample the sequence of numbers that Petya gets as he tries to obtain number b is as follows: 10  →  8  →  6  →  4  →  3  →  2  →  1.

In the second sample one of the possible sequences is as follows: 6  →  4  →  3.


#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <set>
#include <vector>
#include <map>
#include <cmath>
#include <algorithm>
#include <memory.h>
#include <string>
#include <sstream>

using namespace std;

const int m = 360360;

int k;
int f[m+10];

int go(int from, int to) {
int i, j;
for (i=0;i<m;i++) f[i] = 42424242;
  f[from] = 0;
  for (i=m-1;i>=1;i--)
if (f[i] < 42424242) {
      if (f[i]+1 < f[i-1]) f[i-1] = f[i]+1;
      for (j=2;j<=k;j++) {
        int z = i-(i % j);
        if (f[i]+1 < f[z]) f[z] = f[i]+1;
  return f[to];

int main() {
//  freopen("in", "r", stdin);
//  freopen("out", "w", stdout);
  long long a, b;
  cin >> a >> b >> k;
long long ans = 0;
if (a/m == b/m) {
ans = go(a % m, b % m);
} else {
ans = go(a % m, 0);
ans += 1+go(m-1, b % m);
ans += (long long)(1+go(m-1, 0))*(a/m - b/m - 1);
cout << ans << endl;
  return 0;