gpt4 book ai didi

javascript - 如何在输入的数字范围内查找质数

转载 作者:行者123 更新时间:2023-11-28 08:31:34 25 4
gpt4 key购买 nike

我只是想找到输入的数字范围内的素数。我不知道如何计算寻找素数。我需要将它们添加到一个数组中,然后输出该数组。我为计算放置了一个占位符...我似乎不知道如何找到素数。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title>LeapYears</title>

<script type="text/javascript">
/* <![CDATA[ */

function calcPrimeNumber(){

var beginNum = document.numbers.firstNum.value;
var endNum = document.numbers.secondNum.value;
var primeNumbs = new Array();


var ctr = 0;
while (beginNum <= endNum){ //throwaway
if ((beginNum % beginNum == 0) && (beginNum % 1 == 0)){
primeNumbs[ctr] = beginNum;
++ctr;
}

++beginNum;
}

if (primeNumbs == 0){
window.alert("There were no leap years within the range.");
}

else {
outputPrimeNums(primeNumbs);
}

}

function outputPrimeNums(primes){
document.write("<h2>Prime Numbers</h2>");
for (i=0;i<primes.length;i++){
document.write(primes[i] + "<br/>");
}

}


/* ]]> */
</script>


</head>


<body>
<form name="numbers">

Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />

</form>

</body>


</html>

最佳答案

尝试这一整页的 prime no 示例

<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title>LeapYears</title>

<script type="text/javascript">
/* <![CDATA[ */

function calcPrimeNumber(){

var beginNum = parseInt(document.numbers.firstNum.value);
var endNum = parseInt(document.numbers.secondNum.value);
var primeNumbs = new Array();


var ctr = beginNum;
while(ctr<=endNum)
{
if(isPrime(ctr)==true)
{
primeNumbs[primeNumbs.length] = ctr;
}
ctr = ctr+1;

}

if (primeNumbs.length == 0){
document.getElementById('output_content').innerHTML = "There were no prime no within the range.";
}

else {
outputPrimeNums(primeNumbs);
}

}

function isPrime(num)
{
var flag = true;
for(var i=2; i<=Math.ceil(num/2); i++)
{
if((num%i)==0)
{
flag = false;
break;
}
}
return flag;
}

function outputPrimeNums(primes){
var html = "<h2>Prime Numbers</h2>";
for (i=0;i<primes.length;i++){
html += primes[i] + "<br/>";
}
document.getElementById('output_content').innerHTML = html;
}


/* ]]> */
</script>


</head>


<body>
<form name="numbers">

Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />

</form>
<div id="output_content">
</div>
</body>


</html>

关于javascript - 如何在输入的数字范围内查找质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com