import Big from 'big.js';

// Calculate arctan(1/x) using Taylor series
function arctan(x: number, decimals: number): Big {
    const scale = new Big(10).pow(decimals + 10);
    const xSquared = x * x;
    
    let term = scale.div(x);
    let result = new Big(0);
    let n = 0;
    
    while (term.gt(0)) {
        const divisor = 2 * n + 1;
        const contrib = term.div(divisor);
        
        if (n % 2 === 0) {
            result = result.plus(contrib);
        } else {
            result = result.minus(contrib);
        }
        
        term = term.div(xSquared);
        n++;
    }
    
    return result;
}

// Calculate pi using Machin's formula
function calculatePi(decimals: number): string {
    const atan1_5 = arctan(5, decimals);
    const atan1_239 = arctan(239, decimals);
    
    // pi/4 = 4*arctan(1/5) - arctan(1/239)
    // pi = 16*arctan(1/5) - 4*arctan(1/239)
    const pi = atan1_5.times(16).minus(atan1_239.times(4));
    
    // Format with decimal point
    const piStr = pi.toFixed(decimals + 10);
    const digits = piStr.substring(1); // Skip the first digit (3)
    
    let result = '3.';
    for (let i = 0; i < decimals; i++) {
        if (i < digits.length) {
            result += digits[i];
        } else {
            result += '0';
        }
    }
    
    return result;
}

// Main
const decimals = process.argv.length > 2 ? parseInt(process.argv[2]) || 100 : 100;
console.log(calculatePi(decimals));