<?php

// Calculate arctan(1/x) using Taylor series
function arctan($x, $decimals) {
    $scale = bcpow('10', $decimals + 10);
    $xSquared = bcmul($x, $x);
    
    $result = '0';
    $term = bcdiv($scale, $x);
    
    $n = 0;
    while (bccomp($term, '0') != 0 && $n < $decimals * 3) {
        $divisor = (string)(2 * $n + 1);
        $contrib = bcdiv($term, $divisor);
        
        if ($n % 2 == 0) {
            $result = bcadd($result, $contrib);
        } else {
            $result = bcsub($result, $contrib);
        }
        
        $term = bcdiv($term, $xSquared);
        $n++;
        
        if ($n > $decimals * 2) break;
    }
    
    return $result;
}

// Calculate pi using Machin's formula
function calculate_pi($decimals) {
    $atan1_5 = arctan(5, $decimals);
    $atan1_239 = arctan(239, $decimals);
    
    return bcsub(bcmul($atan1_5, '16'), bcmul($atan1_239, '4'));
}

// Format pi with decimal point
function format_pi($pi, $decimals) {
    $piStr = $pi;
    while (strlen($piStr) < $decimals + 10) {
        $piStr = '0' . $piStr;
    }
    return '3.' . substr($piStr, 1, $decimals);
}

// Main
$decimals = isset($argv[1]) ? (int)$argv[1] : 100;
if ($decimals <= 0) $decimals = 100;

$pi = calculate_pi($decimals);
echo format_pi($pi, $decimals) . "\n";
?>