Pages

Thursday 17 January 2013

UVA - 10622 - Perfect P-th Powers

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb = new StringBuffer("");
        while(true){
            int x=Integer.parseInt(br.readLine());
            if(x==0){
                break;
            }
            if(x==1){
                sb.append("1\n");
                continue;
            }
            if(x==Integer.MIN_VALUE){
                sb.append("31\n");
                continue;
            }
            boolean flag=false;
            if(x<0){
                int n = (int) Math.sqrt (x * -1);
                for ( int i = -2; i >= -n; i-- ) {
                    long temp = i;
                    int p = 2;
                    while ( temp > x ) {
                        long sum = i;
                        for ( int j = 2; j < p+1; j++ ) {
                            sum *= i;
                        }
                        temp=sum;
                        p++;
                    }
                    if ( temp == x ) {
                        flag=true;
                            sb.append(p-1).append("\n");
                            break;
                        }
                }
            }else{
                int n = (int) Math.sqrt (x);
                for ( int i = 2; i <n+1; i++ ) {
                    long temp = i;
                    int p = 2;
                    while ( temp < x ) {
                        long sum = i;
                        for ( int j = 2; j < p+1; j++ ) {
                            sum *= i;
                        }
                        temp=sum;
                        p++;
                    }
                    if ( temp == x ) {
                        flag=true;
                            sb.append(p-1).append("\n");
                            break;
                        }
                }
            }
            if(!flag){
                sb.append("1\n");
            }
        }
        System.out.print(sb);
    }
}

No comments:

Post a Comment