Problem:
Greatest Common Divisor

Write a program which finds the greatest common divisor of two natural numbers a and b

Input

a and b are given in a line sparated by a single space.

Output

Output the greatest common divisor of a and b.

Constrants

1 ≤ a, b ≤ 109

Hint

You can use the following observation:

For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y)

Sample Input 1

54 20

Sample Output 1

2

Sample Input 2

147 105

Sample Output 2

21

Solution in JAVA (judge verdict: Accepted)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws IOException {
		ReaderWriter r = new ReaderWriter(); 	// Class to read/write input.
		String ans = "";			// Final answer to be printed.

		int a = r.rInt();
		int b = r.rInt();	
		int temp = 0;

		if(a <= b) {
			temp = a;
			a = b;
			b = temp;
		}

		// When this loop finishes, we have b == 1 or b == 0.
		while( b > 0 ) {
			temp = a;
			a = b;
			b = temp % b;
		}

		ans = Integer.toString(a);

		// Outputs final answer.
		r.pAns(ans);
		r.out.close();
	}


}

class ReaderWriter {
	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;

	public ReaderWriter() {
		// br = new BufferedReader(new FileReader("in.txt"));
		// out = new PrintWriter(new FileWriter("out.txt"));
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(new OutputStreamWriter(System.out));
	}

	String next() throws IOException  {
		while (st == null || !st.hasMoreTokens())
			st = new StringTokenizer(br.readLine().trim());
		return st.nextToken();
	}

	long rLong() throws IOException  {
		return Long.parseLong(next());
	}

	int rInt() throws IOException  {
		return Integer.parseInt(next());
	}

	int[] rIntArray(int n) throws IOException  {
		int[] ret = new int[n];
		for(int i = 0; i < n; i++) {
			ret[i] = rInt();
		}
		return ret;
	}

	double rDouble() throws IOException  {
		return Double.parseDouble(next());
	}

	char rChar() throws IOException  {
		return next().charAt(0);
	}

	String rLine() throws IOException  {
		return br.readLine().trim();
	}

	String wArray(int[] a) throws IOException {
		if(a == null || a.length == 0) {
			return "";
		}
		String ret = "" + a[0];
		for(int i = 1; i < a.length; i++) {
			ret = ret + " " + a[i];
		}
		ret = ret + "\n";
		return ret;
	}

	void pAns(String ans) {
		if(ans.charAt(ans.length()-1) != '\n')
			ans = ans + "\n";
		System.out.print(ans);
	}
}