An efficient Prime Number API using the Sieve of Eratosthenes and MongoDB caching π
β
Fast prime number generation using Sieve of Eratosthenes
β
MongoDB caching for frequently requested values
β
Simple REST API with GET /api/primes/:N
β
Built with Node.js, Express, and MongoDB
The Sieve of Eratosthenes is an ancient algorithm used to find all prime numbers up to a given limit. It works by iteratively marking the multiples of each prime number starting from 2. The numbers which remain unmarked are primes.
- Start with a list of numbers from 2 to
N(the limit). - Starting from 2, mark all of its multiples as non-prime.
- Move to the next unmarked number (it will be a prime), and mark all of its multiples as non-prime.
- Repeat this process until you've processed all numbers up to
N. - The remaining unmarked numbers are primes.
For N = 20:
-
List numbers from 2 to 20:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] -
Mark multiples of 2:
[2, 3, X, 5, X, 7, X, 9, X, 11, X, 13, X, 15, X, 17, X, 19, X] -
Mark multiples of 3:
[2, 3, X, 5, X, 7, X, 9, X, 11, X, 13, X, 15, X, 17, X, 19, X] -
Continue marking multiples of each unmarked number.
After applying the algorithm, the unmarked numbers up to 20 are:

git clone https://github.com/your-username/PrimeSieveAPI.git
cd PrimeSieveAPInpm installMONGO_URI=mongodb://localhost:27017/primeDB
PORT=5000npm run devGET /api/primes/:N{
"primes": [2, 3, 5, 7, 11, 13, 17, 19]
}PrimeSieveAPI/
βββ src/
β βββ models/ # MongoDB Model
β βββ routes/ # API Routes
β βββ controllers/ # API Logic
β βββ db/ # Database Connection
β βββ app.js # Express App
βββ server.js # Server Entry Point
βββ .env # Environment Variables
βββ package.json # Dependencies
βββ README.md # Project Documentationπ Node.js β Backend framework
π Express.js β API routing
π MongoDB β Caching for performance
π Mongoose β Database ORM
π Nodemon β Development utility
πΉ Fork the repo
πΉ Create a new branch (git checkout -b feature-name)
πΉ Commit changes (git commit -m "Added new feature")
πΉ Push to branch (git push origin feature-name)
πΉ Open a Pull Request π

