const express = require('express'); const cors = require('cors'); const app = express(); const Decimal = require('decimal.js'); app.use(cors()); function calculatePi(n) { Decimal.config({ precision: n * 14 }); let pi = new Decimal(0); let k = 0; // Using a simple integer for k let x = new Decimal(1); const sixteen = new Decimal(16); for (let i = 0; i < n; i++) { // Precompute common terms to avoid recalculating them const denominator1 = new Decimal(8).times(k).plus(1); const denominator2 = new Decimal(8).times(k).plus(4); const denominator3 = new Decimal(8).times(k).plus(5); const denominator4 = new Decimal(8).times(k).plus(6); // Calculate the contributions to pi const term1 = Decimal.div(4, denominator1); const term2 = Decimal.div(2, denominator2); const term3 = Decimal.div(1, denominator3); const term4 = Decimal.div(1, denominator4); // Update pi with the calculated terms pi = pi.plus(term1.minus(term2).minus(term3).minus(term4).times(x)); // Increment k and update x k++; x = x.div(sixteen); } return pi; } app.get('/pi', (req, res) => { const precision = parseInt(req.query.precision); if (isNaN(precision)) { return res.status(400).json({ error: 'Invalid precision parameter' }); } const startTime = performance.now(); const pi = calculatePi(precision); const endTime = performance.now(); const duration = (endTime - startTime).toFixed(6); res.json({ pi: pi.toFixed(precision), time: `${duration}ms`, language: 'Node.js' }); }); const PORT = 8083; console.log(`Node.js server starting on port ${PORT}...`); app.listen(PORT);