public class ApproximatePi {
    public static void main(String[] args) {
	int n = Integer.parseInt(args[0]);
	if (n <= 0) {
	    System.out.println("Enter a positive integer");
	    return;
	}
	double tolerance = 1;
	for (int i = 0; i <= n; i++) tolerance /= 10;
	double pi = 4*(arctan(1./2, tolerance) +
		       arctan(1./3, tolerance));
	System.out.println("pi is approximately " + pi);
    }

    public static double arctan(double x, double tolerance) {
	double x2 = x*x;
	double arctan = 0;
	double power = x;
	double denominator = 1;
	double sign = 1;
	while(power/denominator >= tolerance) {
	    arctan += sign*power/denominator;
	    power *= x2;
	    denominator += 2;
	    sign *= -1;
	}
	return arctan;
    }
}
