search
HomeWeb Front-endFront-end Q&AHow to display prime numbers in separate rows in JavaScript

JavaScript is a popular programming language that can be used to create various types of websites and applications. In JavaScript, a prime number is a positive integer that is only divisible by 1 and itself. When we need to display prime numbers on a web page, sometimes we need to display these numbers in separate lines for readability and beauty. This article will introduce how to display prime numbers in separate rows in JavaScript.

  1. Judge prime numbers

To determine whether a number is prime in JavaScript, you can use the following code:

function isPrime(num) {
    for(let i = 2; i <p>This code will loop through from 2 to For all numbers between num-1, check whether it is divisible by num. If it is divisible, it means that num is not a prime number and returns false. Otherwise, continue looping. Finally, if num is not equal to 1, it means it is a prime number and returns true. </p><ol start="2"><li>Display prime numbers in separate lines</li></ol><p>Generally, we will use an array to store the prime numbers we want to display. This array can be dynamically added with prime numbers in a loop. Next, we need a counter to count how many prime numbers are displayed in the current line. When the counter reaches the specified value, we need to display the prime number on a new line. The following code implements this function: </p><pre class="brush:php;toolbar:false">let primes = []; // 存储素数的数组
let rowNum = 10; // 每行显示的素数个数
let count = 0; // 当前行已经显示的素数个数

for(let i = 1; i "); // 换行
            count = 0; // 计数器清零
        }
    }
}

document.write(primes.join(", "));

In this example, we assume that each line displays up to 10 prime numbers. In the loop, if the current number is prime, add it to the array and increment the counter. If the counter is equal to 10, it means that 10 prime numbers have been displayed on the current line and need to be displayed on a new line. We use document.write("
") to wrap the line, clear the counter, and continue the loop.

Finally, we display all the prime numbers on the web page and use the primes.join(", ") function to convert the elements in the array into comma-separated strings.

  1. Further optimization

The above code can realize the function of displaying prime numbers in separate lines, but sometimes we need to adaptively display prime numbers according to the width of the current screen. In this case, we need to dynamically calculate the number of prime numbers displayed in each row. Here's a simple example:

let screenWidth = window.innerWidth; // 获取屏幕宽度
let rowNum = Math.floor(screenWidth / 80); // 根据屏幕宽度计算每行显示的素数个数
let count = 0; // 当前行已经显示的素数个数

In this example, we assume that each prime on the screen is 80 pixels wide. We can use window.innerWidth to get the screen width, and then calculate the number of prime numbers displayed in each line based on the screen width. Finally, we use the count variable to record the number of prime numbers displayed on the current line and wrap the line as needed.

Summary

The line-by-line display of prime numbers in JavaScript requires judging the prime numbers and dynamically calculating the number of prime numbers displayed in each line. Through the above code implementation, we can easily display prime numbers on the web page and adaptively adjust the number of prime numbers displayed in each line as needed, making the web page more beautiful and easier to read.

The above is the detailed content of How to display prime numbers in separate rows in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool