#!/usr/bin/env julia

# Pi calculation using Machin's formula
# pi/4 = 4*arctan(1/5) - arctan(1/239)

# Calculate pi using Machin's formula
function calculate_pi(decimals::Int)
    if decimals < 1
        decimals = 100
    end
    
    # Set precision (need extra bits for accuracy)
    setprecision(decimals * 4 + 100)
    
    # Machin's formula: pi/4 = 4*arctan(1/5) - arctan(1/239)
    pi_val = BigFloat(4) * atan(BigFloat(1)/5) - atan(BigFloat(1)/239)
    pi_val *= 4
    
    # Format output
    pi_str = string(pi_val)
    
    # Extract just the digits we need
    if decimals == 0
        return "3"
    else
        # Find decimal point
        decimal_pos = findfirst('.', pi_str)
        if decimal_pos === nothing
            return pi_str
        end
        
        # Get digits after decimal point
        after_decimal = pi_str[decimal_pos+1:end]
        
        # Pad or truncate to desired length
        if length(after_decimal) < decimals
            after_decimal *= repeat("0", decimals - length(after_decimal))
        else
            after_decimal = after_decimal[1:decimals]
        end
        
        return "3." * after_decimal
    end
end

# Main
function main()
    # Get decimals from command line
    decimals = 100
    if length(ARGS) > 0
        try
            decimals = parse(Int, ARGS[1])
            if decimals < 1
                decimals = 100
            end
        catch
            decimals = 100
        end
    end
    
    result = calculate_pi(decimals)
    println(result)
end

main()