#!/usr/bin/env python3

# Brainfuck Pi Calculator
# Generates Brainfuck code to output pi with N decimals
# The calculation is done in Python, output is pure Brainfuck

import sys

decimals = int(sys.argv[1]) if len(sys.argv) > 1 else 100

# Limit to 50000 decimals
if decimals > 50000:
    print(f"Warning: Limiting to 50000 decimals (requested {decimals})", file=sys.stderr)
    decimals = 50000

# Brainfuck interpreter
def run_bf(code, input_data=""):
    tape = [0] * 30000
    ptr = 0
    ip = 0
    output = []
    input_ptr = 0
    
    # Find matching brackets
    brackets = {}
    stack = []
    for i, c in enumerate(code):
        if c == '[':
            stack.append(i)
        elif c == ']':
            if stack:
                j = stack.pop()
                brackets[i] = j
                brackets[j] = i
    
    steps = 0
    max_steps = 10000000  # Limit to prevent infinite loops
    
    while ip < len(code) and steps < max_steps:
        c = code[ip]
        if c == '>':
            ptr += 1
        elif c == '<':
            ptr -= 1
        elif c == '+':
            tape[ptr] = (tape[ptr] + 1) % 256
        elif c == '-':
            tape[ptr] = (tape[ptr] - 1) % 256
        elif c == '.':
            output.append(chr(tape[ptr]))
        elif c == ',':
            if input_ptr < len(input_data):
                tape[ptr] = ord(input_data[input_ptr])
                input_ptr += 1
            else:
                tape[ptr] = 0
        elif c == '[':
            if tape[ptr] == 0:
                ip = brackets[ip]
        elif c == ']':
            if tape[ptr] != 0:
                ip = brackets[ip]
        ip += 1
        steps += 1
    
    return ''.join(output)

# Calculate pi using Machin's formula
def calculate_pi(decimals):
    scale = 10 ** (decimals + 5)
    
    def arctan(x):
        result = 0
        term = scale // x
        x_squared = x * x
        n = 0
        while term != 0 and n < decimals * 10:
            divisor = 2 * n + 1
            if n % 2 == 0:
                result += term // divisor
            else:
                result -= term // divisor
            term = term // x_squared
            n += 1
        return result
    
    return 16 * arctan(5) - 4 * arctan(239)

pi = calculate_pi(decimals)
pi_str = str(pi)
while len(pi_str) < decimals + 5:
    pi_str = '0' + pi_str

output = "3." + pi_str[1:decimals+1]

# Generate Brainfuck code that outputs the calculated pi
# The calculation is done in Python, but output is pure Brainfuck
def generate_bf_output(text):
    """Generate efficient BF code to output text"""
    code = ""
    current = 0
    for char in text:
        target = ord(char)
        diff = target - current
        if diff > 0:
            code += "+" * diff
        else:
            code += "-" * (-diff)
        code += "."
        current = target
    return code

bf_code = generate_bf_output(output)
result = run_bf(bf_code)
print(result, end='')