You are given an integer n and an integer k.

In one step you can do one of the following moves: 

  * decrease n by 1; 
  * divide n by k if n is divisible by k. 



For example, if n = 27 and k = 3 you can do the following steps: 27 → 26 → 25 → 24 → 8 → 7 → 6 → 2 → 1 → 0.

You are asked to calculate the minimum number of steps to reach 0 from n. 

Input

The first line contains one integer t (1 ≤ t ≤ 100) — the number of queries.

The only line of each query contains two integers n and k (1 ≤ n ≤ 10^{18}, 2 ≤ k ≤ 10^{18}).

Output

For each query print the minimum number of steps to reach 0 from n in single line. 

Example

Input


2
59 3
1000000000000000000 10


Output


8
19

Note

Steps for the first test case are: 59 → 58 → 57 → 19 → 18 → 6 → 2 → 1 → 0.

In the second test case you have to divide n by k 18 times and then decrease n by 1.
import java.io.BufferedReader;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import static java.lang.Math.sqrt;
import static java.lang.Math.round;
import java.lang.Math;
public class Jo {
	public static void main(String args[]) throws IOException 
    { 
		Scanner sc=new Scanner(System.in);
		
		int t=sc.nextInt();
		
		while(t-->0) {
			long n=sc.nextLong();
			long k=sc.nextLong();long s=0;
		while(n>0) {
			if(n%k==0) {
				n/=k;s++;
			}
			else {
				s+=(n%k);n=n-(n%k);
				//System.out.println(s);
			}
			
			//System.out.println(n+" "+s);
		}
		System.out.println(s);
    }
		//System.out.println(59/3);
    }	
	
	//count number of digits of number n
	static long countDigit(long n) 
    { 
        return (long)Math.floor(Math.log10(n) + 1); 
    } 
    //min. summation of pairs of divisors
	public static int di(int n) {
		int s;int min=1000000;
		for(int i=1;i*i<=n;i++) {
			if(n%i==0) {
				s=i+(n/i);
				if(s<=min)min=s;
			}
		}
		return min;
	}
	
	public static double squareRoot(int number) {
		double temp;

		double sr = number / 2;

		do {
			temp = sr;
			sr = (temp + (number / temp)) / 2;
		} while ((temp - sr) != 0);

		return sr;
	    }
	static boolean isPerfect(int n) 
    { 
        // To store sum of divisors 
        int sum = 1; 
      
        // Find all divisors and add them 
        for (int i = 2; i * i <= n; i++) 
        { 
            if (n % i==0) 
            { 
                if(i * i != n) 
                    sum = sum + i + n / i; 
                else
                    sum = sum + i; 
            } 
        }  
        // If sum of divisors is equal to 
        // n, then n is a perfect number 
        if (sum == n && n != 1) 
            return true; 
      
        return false; 
    } 
}