import java.math.BigInteger
import kotlin.system.exitProcess

// Calculate arctan(1/x) using Taylor series
// arctan(1/x) = 1/x - 1/(3*x^3) + 1/(5*x^5) - ...
fun arctan(x: Int, decimals: Int): BigInteger {
    val scale = BigInteger.TEN.pow(decimals + 10)
    val xBig = BigInteger.valueOf(x.toLong())
    val xSquared = xBig * xBig
    
    var term = scale / xBig
    var result = BigInteger.ZERO
    var n = 0
    
    while (term != BigInteger.ZERO && n < decimals * 3) {
        val divisor = BigInteger.valueOf(2L * n + 1)
        val contrib = term / divisor
        
        if (n % 2 == 0) {
            result += contrib
        } else {
            result -= contrib
        }
        
        term = term / xSquared
        n++
    }
    
    return result
}

fun calculatePi(decimals: Int): BigInteger {
    val atan1_5 = arctan(5, decimals)
    val atan1_239 = arctan(239, decimals)
    
    // pi = 16*arctan(1/5) - 4*arctan(1/239)
    return atan1_5 * BigInteger.valueOf(16) - atan1_239 * BigInteger.valueOf(4)
}

fun main(args: Array<String>) {
    var decimals = 100
    
    if (args.isNotEmpty()) {
        try {
            decimals = args[0].toInt()
            if (decimals < 1) decimals = 100
        } catch (e: NumberFormatException) {
            decimals = 100
        }
    }
    
    val pi = calculatePi(decimals)
    val piStr = pi.toString()
    
    // Print with decimal point
    print("3.")
    val startIndex = 1
    val endIndex = minOf(startIndex + decimals, piStr.length)
    print(piStr.substring(startIndex, endIndex))
    
    // Pad with zeros if needed
    for (i in 0 until decimals - (endIndex - startIndex)) {
        print("0")
    }
    println()
}