Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- /**
- * Created by zxc on 05.10.2014.
- */
- public class G {
- long n;
- long k;
- long P=0;
- void f(long n){
- if (n>k)
- {
- long p=1;
- int x=0;
- while(Math.pow(k, x+1)<n)
- {
- x++;
- if (x%2==1)
- p=p*k;
- }
- P=P+(long)(n/Math.pow(k,x))*p;
- f((long)(n-((int)(n/Math.pow(k,x))*Math.pow(k,x))));
- }
- else
- P+=n;
- }
- void solve() throws IOException {
- n=nextLong();
- k=nextLong();
- if (k%2==0)
- f(n+1);
- else
- f(n);
- out.println(P);
- }
- void run() throws IOException {
- reader = new BufferedReader(new InputStreamReader(System.in));
- out = new PrintWriter(new OutputStreamWriter(System.out));
- // reader = new BufferedReader(new FileReader("file.in"));
- // out = new PrintWriter(new FileWriter("file.out"));
- tokenizer = null;
- solve();
- reader.close();
- out.flush();
- }
- public static void main(String[] args) throws IOException {
- new G().run();
- }
- BufferedReader reader;
- StringTokenizer tokenizer;
- PrintWriter out;
- int nextInt() throws IOException {
- return Integer.parseInt(nextToken());
- }
- long nextLong() throws IOException {
- return Long.parseLong(nextToken());
- }
- double nextDouble() throws IOException {
- return Double.parseDouble(nextToken());
- }
- String nextToken() throws IOException {
- while (tokenizer == null || !tokenizer.hasMoreTokens()) {
- tokenizer = new StringTokenizer(reader.readLine());
- }
- return tokenizer.nextToken();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement