Today, we explored recursion in depth and learned how to solve problems like factorial computation, GCD (Greatest Common Divisor), and finding factors of a number using recursion. π₯
The GCD (HCF - Highest Common Factor) of two numbers is the largest number that divides both numbers completely.
- Start from the minimum of two numbers and check divisibility.
- Decrease the divisor (
c
) until the GCD is found.
let a = 20;
let b = 32;
let c = a < b ? a : b;
console.log(findGCD(a, b, c));
function findGCD(a, b, c) {
if (c == 1) return c;
if (a % c == 0 && b % c == 0) return c;
return findGCD(a, b, c - 1);
}
β³ Time Complexity: O(min(a, b))
πΉ The Euclidean algorithm reduces the problem by subtracting the smaller number from the larger one.
πΉ This is much faster than iterating from min(a, b) downwards.
console.log(GCD(20, 32));
function GCD(a, b) {
if (a == b) return a;
if (a > b) return GCD(a - b, b);
else return GCD(a, b - a);
}
πΉ Time Complexity: O(log(min(a, b)))
β Most efficient way to find GCD using recursion! β
This function prints numbers from n to 1 recursively. π
let n = 5;
temp(n);
function temp(n) {
if (n == 0) return;
console.log(n);
temp(--n);
}
β This function decrements n
until 0
is reached.
πΉ A factor of n
is any number that divides n
completely.
πΉ We recursively check divisibility starting from 1
.
let n = 50;
factor(n, 1);
function factor(n, i) {
if (n % i == 0) console.log(i); // Print factor
if (i > Math.floor(n / 2)) {
console.log(n); // Print n itself as a factor
return;
}
factor(n, i + 1);
}
β Time Complexity: O(n/2)
Instead of checking all numbers up to n/2
, we only go up to sqrt(n)
, which is more efficient.
function printFactors(n) {
let result = [];
for (let i = 1; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
if (i === n / i) {
result.push(i);
} else {
result.push(i);
result.push(n / i);
}
}
}
result.sort((a, b) => a - b);
console.log(result.join(", "));
}
printFactors(50);
β Time Complexity: O(βn)
(Much Faster!)
β
Recursion is a powerful concept that helps break problems into smaller instances of the same problem.
β
GCD can be optimized using the Euclidean algorithm.
β
Factorization can be optimized by checking only up to sqrt(n)
instead of n/2
.
π₯ Keep practicing recursion, and you'll master it in no time! ππ‘
Today, we built a User Management System using Express, MongoDB (Mongoose), and EJS! π
We started by setting up our Node.js project:
npm init -y
npm i ejs mongoose express
This installs:
- EJS for templating πΌοΈ
- Mongoose for database interaction π’οΈ
- Express for handling routes π
Our form collects:
β Username
β Email
β Bio
β Profile Image (URL)
π Route to Render the Form:
app.get("/create", (req, res) => {
res.render("createUser"); // Renders EJS form
});
π EJS Form (views/createUser.ejs
):
<form action="/create" method="POST">
<input type="text" name="username" placeholder="Enter Username" required />
<input type="email" name="email" placeholder="Enter Email" required />
<textarea name="bio" placeholder="Enter Bio"></textarea>
<input type="text" name="profileImage" placeholder="Enter Profile Image URL" />
<button type="submit">Create User</button>
</form>
We post the form data to /create and store it in our MongoDB database.
π Mongoose User Schema (models/user.model.js
):
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
username: String,
email: String,
bio: String,
profileImage: String
});
const User = mongoose.model("User", userSchema);
module.exports = User;
π Handling Form Submission in Express (routes/userRoutes.js
)
const User = require("../models/user.model");
app.post("/create", async (req, res) => {
try {
const { username, email, bio, profileImage } = req.body;
await User.create({ username, email, bio, profileImage });
res.redirect("/users"); // Redirect to users list after creation
} catch (error) {
res.status(500).send("Error creating user");
}
});
We now fetch all users and display them as cards! π
π Fetching Users (routes/userRoutes.js
)
app.get("/users", async (req, res) => {
const users = await User.find();
res.render("users", { users });
});
π EJS Template to Show Users (views/users.ejs
)
<% users.forEach(user => { %>
<div class="card">
<img src="<%= user.profileImage %>" alt="Profile" />
<h2><%= user.username %></h2>
<a href="/userDetails/<%= user._id %>">View Profile</a>
</div>
<% }); %>
When clicking a user card, it redirects to userDetails/:user_id π
π Route for User Details (routes/userRoutes.js
)
app.get("/userDetails/:user_id", async (req, res) => {
const user = await User.findById(req.params.user_id);
res.render("userDetails", { user });
});
π EJS Template for User Details (views/userDetails.ejs
)
<div class="profile">
<img src="<%= user.profileImage %>" alt="Profile" />
<h2><%= user.username %></h2>
<p>Email: <%= user.email %></p>
<p>Bio: <%= user.bio %></p>
</div>
β
Form to Create Users
β
Store Users in MongoDB
β
Display Users as Cards
β
Click on User Card to View Full Profile
π Awesome Work! Keep Learning! π‘π₯