Check if a Number is Prime in Python

Hello connections 👋 Welcome to Day 6 of my Python problem-solving series! Consistency and practice make coding easier every day 🚀 🧠 Day 6 Challenge: Check if a Number is Prime Write a Python program to check whether a given number is prime or not. 👉 Example: Input: 7 → Output: Prime Input: 9 → Output: Not Prime My Approach 1: Basic Method (Factor Count) num = int(input("Enter a number: ")) c= 0 if num <= 1: print("Not Prime") else: for i in range(1, num + 1): if num % i == 0: c += 1 if c == 2: print("Prime") else: print("Not Prime") 📌 Explanation: A prime number has exactly 2 factors: 1 and itself. My Approach 2: Optimized Method (Using √n) num = int(input("Enter a number: ")) if num <= 1: print("Not Prime") else: for i in range(2, int(num**0.5) + 1): if num % i == 0: print("Not Prime") break else: print("Prime") 📌 Explanation: We only check divisibility up to √n, making it faster for large numbers. Now it’s your turn 👇 Try solving it with your own logic or suggest a better approach in the comments. Let’s learn and grow together 🚀 #Python #CodingChallenge #ProblemSolving #Programming #30DaysOfCode

To view or add a comment, sign in

Explore content categories