惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AWS News Blog
AWS News Blog
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
博客园 - 聂微东
Security Archives - TechRepublic
Security Archives - TechRepublic
酷 壳 – CoolShell
酷 壳 – CoolShell
Cisco Talos Blog
Cisco Talos Blog
人人都是产品经理
人人都是产品经理
I
Intezer
C
CERT Recently Published Vulnerability Notes
博客园 - 三生石上(FineUI控件)
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
The Register - Security
The Register - Security
F
Full Disclosure
Scott Helme
Scott Helme
Cyberwarzone
Cyberwarzone
U
Unit 42
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
NISL@THU
NISL@THU
T
Tor Project blog
A
Arctic Wolf
Y
Y Combinator Blog
I
InfoQ
M
MIT News - Artificial intelligence
P
Privacy & Cybersecurity Law Blog
Know Your Adversary
Know Your Adversary
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
Latest news
Latest news
量子位
N
News and Events Feed by Topic
T
The Blog of Author Tim Ferriss
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园_首页
S
Securelist
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
The Cloudflare Blog
The GitHub Blog
The GitHub Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Find a Prime Number in Python — A Thinking Journey
Kathirvel S · 2026-06-01 · via DEV Community

Introduction

Understanding how to find prime numbers is one of the best ways to develop logical thinking in programming. It looks simple on the surface, but it teaches you how to break a problem into smaller steps, build a solution gradually, and then improve it into a clean and reusable structure.

In this blog, we will not jump directly into code. Instead, we will start from basic thinking, slowly convert that thinking into logic, and finally refine it into a proper Python program using functions and loops. The goal is not just to find prime numbers, but to understand how programming logic is actually built in real development.


1. Understanding the Problem First

Before writing anything in Python, we need to understand what a prime number actually means.

A prime number is a number that:

  • is greater than 1
  • has exactly two divisors: 1 and itself

So the real question becomes:

How do we check whether a number has any divisors other than 1 and itself?

That is the core problem we are trying to solve.


2. Thinking Like a Human Before Coding

Let’s take a number, for example 13.

To check if 13 is prime, we naturally try dividing it by smaller numbers:

  • 2 → does not divide 13
  • 3 → does not divide 13
  • 4 → does not divide 13
  • 5 → does not divide 13
  • and so on

If none of these numbers divide 13 completely, then 13 is prime.

So the logic is simple:

Try dividing the number by possible candidates and see if any divide it perfectly.


3. Turning Thinking into a Basic Algorithm

From the above idea, we can form a basic structure:

We need:

  • a number to test
  • a variable that moves through possible divisors
  • a way to detect whether a divisor exists

We start checking from 2 because every number is divisible by 1 anyway.

We also do not need to check beyond half of the number, because a number cannot have a divisor greater than half (except itself).

So the idea becomes:

  • Start divisor from 2
  • Go up to number // 2
  • If any number divides it evenly, it is not prime

4. First Working Logic (Direct Implementation)

Now we translate the idea into Python.

We introduce:

  • number: the value we are testing
  • divisor: the number we try dividing with
  • divisor_count: how many divisors we find

If divisor_count stays zero, the number is prime.

number = 13
divisor = 2
divisor_count = 0

while divisor <= number // 2:
    if number % divisor == 0:
        print("divisor found:", divisor)
        divisor_count += 1
    divisor += 1

if divisor_count == 0:
    print("Prime")
else:
    print("Not Prime")

Flow Chart:

Start
  ↓
Initialize number, divisor = 2, divisor_count = 0
  ↓
Check divisor <= number//2
  ↓
Is number divisible by divisor?
      ↓ Yes → increment divisor_count
      ↓ No  → continue
  ↓
Increase divisor
  ↓
Repeat loop
  ↓
If divisor_count == 0 → Prime
Else → Not Prime
  ↓
End


5. Understanding What Happens Here

This logic works like a manual test:

We are checking every possible divisor one by one.

If even one divisor divides the number completely, we mark it as non-prime.

Otherwise, it is prime.

So effectively:

  • No divisors found → Prime
  • At least one divisor found → Not Prime

6. The Problem With This Approach

Although this works, it has a major issue.

If we want to check multiple numbers, we would need to repeat the same logic again and again.

This leads to:

  • repeated code
  • harder maintenance
  • low reusability

So we need a better structure.


7. Introducing Functions in Python

A function is a reusable block of code that performs a specific task.

Instead of rewriting logic every time, we can define it once and reuse it whenever needed.

From the official Python documentation:

A function is a group of statements that performs a specific task.

Reference:
https://docs.python.org/3/tutorial/controlflow.html#defining-functions


8. Simple Example to Understand Functions

Before applying it to primes, let’s understand a simple function idea.

def buy_nonveg():
    return "chicken"

bag = buy_nonveg()
print(bag)

Flow Chart:

Call function buy_nonveg()
  ↓
Execute function body
  ↓
return "chicken"
  ↓
Store result in bag
  ↓
Print bag
  ↓
End


9. Understanding the return Keyword

The return statement is used to send a result back from a function.

From Python documentation:

The return statement exits a function and optionally passes back an expression.

Reference:
https://docs.python.org/3/reference/simple_stmts.html#the-return-statement

In simple terms:

  • A function processes something
  • return sends the result back
  • after return, the function stops executing

You can think of it as:

Input → Processing → Output

return is the output step.


10. Converting Prime Logic into a Function

Now we take our earlier logic and wrap it inside a function so it becomes reusable.

def find_prime(no):
    div = 2
    divisors_count = 0

    while div <= no // 2:
        if no % div == 0:
            divisors_count += 1
        div += 1

    if divisors_count == 0:
        return True
    else:
        return False

Flow Chart:

Start function find_prime(no)
  ↓
Initialize div = 2, divisors_count = 0
  ↓
Check div <= no//2
  ↓
Is no divisible by div?
      ↓ Yes → increment divisors_count
      ↓ No  → continue
  ↓
Increase div
  ↓
Repeat loop
  ↓
If divisors_count == 0
      ↓ Yes → return True
      ↓ No  → return False
  ↓
End function


11. Understanding This Function

This function does the following:

  • takes a number as input
  • checks all possible divisors
  • counts how many divisors exist
  • returns True if no divisors are found
  • returns False otherwise

So now instead of writing full logic every time, we simply call this function.


12. Using the Function (But Still Not Efficient)

Now we try to use this function to check multiple numbers.

no = 2

result = find_prime(no)
if result == True:
    print(no)

no += 1
result = find_prime(no)
if result == True:
    print(no)

no += 1
result = find_prime(no)
if result == True:
    print(no)

Flow Chart:

Start
  ↓
Set no = 2
  ↓
Call find_prime(no)
  ↓
If result == True → print no
  ↓
Increase no
  ↓
Repeat manually
  ↓
End


13. The Problem Again

Even though logic is now reusable, usage is still repetitive.

We are still manually:

  • increasing numbers
  • calling function again and again

This is not scalable.

So we need another improvement.


14. Using a Loop to Remove Repetition

Instead of repeating the same steps, we can automate the process using a loop.

def find_prime(no):
    div = 2
    divisors_count = 0

    while div <= no // 2:
        if no % div == 0:
            divisors_count += 1
        div += 1

    return divisors_count == 0


no = 2

while no <= 10:
    if find_prime(no):
        print(no)
    no += 1

Flow Chart:

Start
  ↓
Set no = 2
  ↓
Check no <= 10
  ↓
Call find_prime(no)
  ↓
If True → print no
  ↓
Increment no
  ↓
Repeat loop
  ↓
End when no > 10


15. What Changed Here

Now the structure is much cleaner:

  • Loop handles number progression
  • Function handles prime checking
  • Output is handled separately

This separation is important in programming design.


16. Final Improved Version (Cleaner Logic)

We can further improve the function by removing unnecessary counting.

We only need to know whether a divisor exists or not.

def is_prime(n):
    if n < 2:
        return False

    div = 2
    while div <= n // 2:
        if n % div == 0:
            return False
        div += 1

    return True

Flow Chart:

Start function is_prime(n)
  ↓
If n < 2 → return False
  ↓
Set div = 2
  ↓
Check div <= n//2
  ↓
If n % div == 0 → return False
  ↓
Increment div
  ↓
Repeat loop
  ↓
If no divisor found → return True
  ↓
End function

And usage becomes:

for num in range(2, 11):
    if is_prime(num):
        print(num)

Flow Chart:

Start
  ↓
Loop num from 2 to 10
  ↓
Call is_prime(num)
  ↓
If True → print num
  ↓
Repeat loop
  ↓
End


17. Final Understanding

At a high level, prime checking is simply:

  • Try dividing the number
  • If anything divides it evenly → not prime
  • If nothing divides it → prime

Everything else in code is just structuring this idea properly.


18. Key Learning Path

What we built step by step:

  1. Manual reasoning
  2. Basic loop logic
  3. First implementation
  4. Identifying repetition problem
  5. Introducing functions
  6. Understanding return
  7. Refactoring into reusable design
  8. Removing redundancy with loops
  9. Final clean implementation

Conclusion

What looks like a simple “prime number program” is actually a complete demonstration of how programming logic evolves in real software development.

We started with raw human thinking, converted it into a working algorithm, noticed its limitations, introduced functions for reusability, and finally optimized it into a clean and scalable solution.

This is exactly how real developers think: not by writing perfect code at once, but by building, observing problems, and improving step by step.

If you understand this flow, you are not just learning prime numbers — you are learning how to think like a programmer.