Advertisement
Guest User

1

a guest
Nov 28th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. /**
  5.  * Created by zxc on 05.10.2014.
  6.  */
  7. public class G {
  8.     long n;
  9.     long k;
  10.     long P=0;
  11.     void f(long n){
  12.         if (n>k)
  13.         {
  14.             long p=1;
  15.             int x=0;
  16.             while(Math.pow(k, x+1)<n)
  17.             {
  18.                 x++;
  19.                 if (x%2==1)
  20.                     p=p*k;
  21.             }
  22.             P=P+(long)(n/Math.pow(k,x))*p;
  23.             f((long)(n-((int)(n/Math.pow(k,x))*Math.pow(k,x))));
  24.         }
  25.         else
  26.             P+=n;
  27.     }
  28.     void solve() throws IOException {
  29.         n=nextLong();
  30.         k=nextLong();
  31.         if (k%2==0)
  32.             f(n+1);
  33.         else
  34.             f(n);
  35.         out.println(P);
  36.     }
  37.    
  38.  
  39.  
  40.    
  41.    
  42.     void run() throws IOException {
  43.         reader = new BufferedReader(new InputStreamReader(System.in));
  44.         out = new PrintWriter(new OutputStreamWriter(System.out));
  45.         // reader = new BufferedReader(new FileReader("file.in"));
  46.         // out = new PrintWriter(new FileWriter("file.out"));
  47.         tokenizer = null;
  48.         solve();
  49.         reader.close();
  50.         out.flush();
  51.     }
  52.  
  53.     public static void main(String[] args) throws IOException {
  54.         new G().run();
  55.     }
  56.  
  57.     BufferedReader reader;
  58.     StringTokenizer tokenizer;
  59.     PrintWriter out;
  60.  
  61.     int nextInt() throws IOException {
  62.         return Integer.parseInt(nextToken());
  63.     }
  64.  
  65.     long nextLong() throws IOException {
  66.         return Long.parseLong(nextToken());
  67.     }
  68.  
  69.     double nextDouble() throws IOException {
  70.         return Double.parseDouble(nextToken());
  71.     }
  72.  
  73.     String nextToken() throws IOException {
  74.         while (tokenizer == null || !tokenizer.hasMoreTokens()) {
  75.             tokenizer = new StringTokenizer(reader.readLine());
  76.         }
  77.         return tokenizer.nextToken();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement