#!/usr/bin/env Rscript

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

# Load gmp package for big integers
library(gmp)

# Calculate arctan(1/x) using Taylor series
# arctan(1/x) = 1/x - 1/(3*x^3) + 1/(5*x^5) - ...
arctan <- function(x, decimals) {
  scale <- as.bigz(10)^(decimals + 10)
  x_big <- as.bigz(x)
  x_sq <- x_big * x_big
  
  term <- scale %/% x_big
  result <- as.bigz(0)
  n <- 0
  
  while (term != 0 && n < decimals * 3) {
    divisor <- as.bigz(2 * n + 1)
    contrib <- term %/% divisor
    
    if (n %% 2 == 0) {
      result <- result + contrib
    } else {
      result <- result - contrib
    }
    
    term <- term %/% x_sq
    n <- n + 1
  }
  
  return(result)
}

# Main function
main <- function() {
  args <- commandArgs(trailingOnly = TRUE)
  decimals <- 100
  
  if (length(args) > 0) {
    decimals <- as.integer(args[1])
    if (is.na(decimals) || decimals < 1) {
      decimals <- 100
    }
  }
  
  # Calculate arctan(1/5) and arctan(1/239)
  atan1_5 <- arctan(5, decimals)
  atan1_239 <- arctan(239, decimals)
  
  # pi = 16*arctan(1/5) - 4*arctan(1/239)
  pi_val <- atan1_5 * as.bigz(16) - atan1_239 * as.bigz(4)
  
  # Convert to string
  pi_str <- as.character(pi_val)
  
  # Print with decimal point
  cat("3.")
  
  # Extract digits after the first digit (which is 3)
  if (nchar(pi_str) > 1) {
    # Skip the first digit (3) and take the rest
    digits <- substring(pi_str, 2)
    if (nchar(digits) >= decimals) {
      cat(substr(digits, 1, decimals))
    } else {
      cat(digits)
      # Pad with zeros if needed
      for (i in 1:(decimals - nchar(digits))) {
        cat("0")
      }
    }
  } else {
    # Pad with zeros
    for (i in 1:decimals) {
      cat("0")
    }
  }
  
  cat("\n")
}

main()