Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Prime Number Program in Java
Next article icon

JavaScript Application To Check Prime and Non-Prime Number

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Prime numbers have been a fundamental concept in mathematics and computer science. In programming, checking if a number is prime will help to understand loops, conditions, and optimization techniques.

What We Are Going to Create

We will create a simple web application where users can input a number to check if it’s a Prime or Non-Prime number. The application will:

  • Accept a number as input from the user.
  • Check whether the number is prime or non-prime.
  • Display the result to the user.

Project Preview

Prime-and-NonPrime
JavaScript Application To Check Prime and Non-Prime Number

Prime and Non-Prime Number - HTML & CSS  Structure

This structure provides a simple web interface with an input field to enter a number and a button to check whether the number is prime or non-prime

HTML
<html>
<head>
    <title>Prime Number Checker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f9;
        }

        .container {
            text-align: center;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        input {
            padding: 10px;
            width: 200px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        #result {
            margin-top: 20px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Prime Number Checker</h1>
        <input type="number" id="input" placeholder="Enter a number">
        <button onclick="cPrime()">Check</button>
        <p id="result"></p>
    </div>
</body>
</html>

In this example

  • body: Uses Flexbox to center content both vertically and horizontally, with a light gray background and no margins.
  • .container: A white box with rounded corners, padding, and a shadow for a card-like appearance.
  • input: Styled for usability with padding, a defined width, light border, and rounded corners.
  • button: Green background, white text, rounded corners, and a hover effect for better interaction.
  • #result: Displays output with spacing and a larger font size for visibility.

Prime and Non-Prime Number - JavaScript Functionality

The JavaScript function checks if a number is prime by iterating from 2 to the square root of the number. If the number is divisible by any value in this range, it's marked as non-prime otherwise, it is prime.

JavaScript
function cPrime() {
    const n = parseInt(document.getElementById('input').value);
    const res = document.getElementById('result');
    if (isNaN(n) || n <= 1) {
        res.textContent = "Please enter a number greater than 1.";
        res.style.color = "red";
        return;
    }
    let isPrime = true;
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            isPrime = false;
            break;
        }
    }
    if (isPrime) {
        res.textContent = `${n} is a Prime Number.`;
        res.style.color = "green";
    } else {
        res.textContent = `${n} is a Non-Prime Number.`;
        res.style.color = "blue";
    }
}

In this example

  • The function retrieves the user input as a number from an input field with the ID input.
  • It checks if the input is valid (a number greater than 1); otherwise, it displays an error message in red.
  • A flag variable isPrime is initialized as true to track if the number is prime.
  • A for loop iterates from 2 to the square root of the input number to check divisibility. If any divisor is found, isPrime is set to false and the loop breaks.
  • If the number is prime, a success message is displayed in green; otherwise, a non-prime message is shown in blue.
  • The result is dynamically updated in an element with the ID result.

Complete Code

HTML
<html>
<head>
    <title>Prime Number Checker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f9;
        }

        .container {
            text-align: center;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        input {
            padding: 10px;
            width: 200px;
            margin: 10px 0;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        #result {
            margin-top: 20px;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Prime Number Checker</h1>
        <input type="number" id="input" placeholder="Enter a number">
        <button onclick="cPrime()">Check</button>
        <p id="result"></p>
    </div>
    <script>
        function cPrime() {
            const n = parseInt(document.getElementById('input').value);
            const res = document.getElementById('result');
            if (isNaN(n) || n <= 1) {
                res.textContent = "Please enter a number greater than 1.";
                res.style.color = "red";
                return;
            }
            let isPrime = true;
            for (let i = 2; i <= Math.sqrt(n); i++) {
                if (n % i === 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                res.textContent = `${n} is a Prime Number.`;
                res.style.color = "green";
            } else {
                res.textContent = `${n} is a Non-Prime Number.`;
                res.style.color = "blue";
            }
        }
    </script>
</body>
</html>

Next Article
Prime Number Program in Java

T

tanmxcwi
Improve
Article Tags :
  • HTML
  • JavaScript-Projects

Similar Reads

    Prime Number Program in Java
    A prime number is a natural number greater than 1, divisible only by 1 and itself. Examples include 2, 3, 5, 7, and 11. These numbers have no other factors besides themselves and one.In this article, we will learn how to write a prime number program in Java when the input given is a Positive number.
    6 min read
    Prime Number Program in Java
    A prime number is a natural number greater than 1, divisible only by 1 and itself. Examples include 2, 3, 5, 7, and 11. These numbers have no other factors besides themselves and one.In this article, we will learn how to write a prime number program in Java when the input given is a Positive number.
    6 min read
    Prime Number Program in Java
    A prime number is a natural number greater than 1, divisible only by 1 and itself. Examples include 2, 3, 5, 7, and 11. These numbers have no other factors besides themselves and one.In this article, we will learn how to write a prime number program in Java when the input given is a Positive number.
    6 min read
    Quick ways to check for Prime and find next Prime in Java
    Many programming contest problems are somehow related Prime Numbers. Either we are required to check Prime Numbers, or we are asked to perform certain functions for all prime number between 1 to N. Example: Calculate the sum of all prime numbers between 1 and 1000000. Java provides two function unde
    2 min read
    Prime Number Program | Code to Check whether a number is Prime or not
    Given a positive integer n, write a code to check whether the number is prime. What is Prime Number?A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of the first few prime numbers are {2, 3, 5, ...}Examples:Input: n = 11Output: trueInput: n =
    12 min read
    JavaScript Program to Check Prime Number By Creating a Function
    A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we will explore how to check if a given number is a prime number in JavaScript by creating a function. Table of Content Check Prime Number using for LoopCheck Prime Number using
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences