Prime Factors Challenge: Brute Force vs Optimal Approach

Day 19 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Print All Prime Factors of a Number We were given an integer N. We had to print all its prime factors. This one was more number theory based. Let’s understand it simply. ◾️Imagine you want to break a number into its smallest building blocks. ◾️Those building blocks must be prime. ◾️When you multiply them back, you should get the original number. That’s prime factorization. --- 💻 Brute Force Approach 🔹️Start from 2 till n. 🔹️Check if i divides n. 🔹️If yes, check if i is prime. 🔹️If prime, add it to list. Time Complexity: Higher. Because we check many numbers. Works. But not efficient. --- 💻 Optimal Approach 🔹️Start from 2 till √n. 🔹️If i divides n, add it to list. 🔹️Keep dividing n by i in a while loop. 🔹️Remove repeated factors. 🔹️Continue till √n. 🔹️If remaining n > 1, it is also a prime factor. Time Complexity: O(√N) Space Complexity: O(√N) Much better than checking till n. --- 📚 What I learned today: ▫️We don’t need to check till n. √n is enough. ▫️Repeated division reduces unnecessary checks. ▫️Prime factor problems are about observation. ▫️Number theory concepts are important for coding interviews. Day 19 completed. Math + logic together today 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic

To view or add a comment, sign in

Explore content categories