#!/usr/bin/perl
use strict;
use warnings;
use Math::BigInt;

# Calculate arctan(1/x) using Taylor series
sub arctan {
    my ($x, $decimals) = @_;
    
    my $scale = Math::BigInt->new(10)->bpow($decimals + 10);
    my $x_squared = $x * $x;
    
    my $term = $scale->copy()->bdiv($x);
    my $result = Math::BigInt->new(0);
    my $n = 0;
    
    while ($term > 0) {
        my $divisor = 2 * $n + 1;
        my $contrib = $term->copy()->bdiv($divisor);
        
        if ($n % 2 == 0) {
            $result->badd($contrib);
        } else {
            $result->bsub($contrib);
        }
        
        $term = $term->copy()->bdiv($x_squared);
        $n++;
    }
    
    return $result;
}

# Calculate pi using Machin's formula
sub calculate_pi {
    my ($decimals) = @_;
    
    my $atan1_5 = arctan(5, $decimals);
    my $atan1_239 = arctan(239, $decimals);
    
    # pi = 16*arctan(1/5) - 4*arctan(1/239)
    my $pi = $atan1_5->copy()->bmul(16)->bsub($atan1_239->copy()->bmul(4));
    
    # Format with decimal point
    my $pi_str = $pi->bstr();
    
    my $result = "3.";
    my $start = 1;
    
    for (my $i = 0; $i < $decimals; $i++) {
        if ($start + $i < length($pi_str)) {
            $result .= substr($pi_str, $start + $i, 1);
        } else {
            $result .= "0";
        }
    }
    
    return $result;
}

# Main
my $decimals = 100;
if (@ARGV > 0) {
    $decimals = $ARGV[0] =~ /^\d+$/ ? $ARGV[0] : 100;
}

print calculate_pi($decimals) . "\n";