Saturday, 11 February 2012

Codechef -> Practice -> Easy -> GCD2



Solution :



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author XCoder
 */
class GCD2 {

    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static PrintWriter pw = new PrintWriter(System.out);

    public static int readIntLine() throws IOException {
        return Integer.parseInt(br.readLine());
    }

    public static long readLongLine() throws IOException {
        return Long.parseLong(br.readLine());
    }

    public static void main(String[] args) throws IOException {
        int test = readIntLine();
        while (test-- > 0) {
            String str = br.readLine();
            int a = Integer.parseInt(str.split(" ")[0]);
            char b[] = str.split(" ")[1].toCharArray();

            int k = 0;
            for (int i = b.length - 1; i >= 0; i--) {
                k = k * 10 + (b[i] - '0');
//                System.out.println(k + "  " + a);
                k = k % a;
//                System.out.println(k);
            }
            k = gcd(a, k);
            pw.println(k);
        }
        pw.flush();
        pw.close();
    }

    public static int gcd(int a, int b) {
        if (b!=0 && a % b == 0) {
            return b;
        } else if (b == 0) {
            return a;
        }
        return gcd(a, a % b);
    }
}

No comments:

Post a Comment