问题描述
这是一个问题:如果整数大于1且只能被1及其自身整除,则将其称为质数.例如,2、3、5和7是质数,而4、6、8和9不是质数.
this is the Question: An integer is said to be prime if it is greater than 1 and divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a)编写一个确定数字是否为质数的函数.b)在确定并打印1到10000之间的所有质数的脚本中使用此功能.
a) Write a function that determines whether a number is prime.b) Use this function in a script that determines and prints all the prime numbers between 1 and 10000.
在确定已找到所有质数之前,您真的必须测试这10000个数字中的多少个?在< textrarea>
中显示结果.
How many of these 10000 numbers do you really have to test before being sure that you have found all the primes? Display the results in a <textrarea>
.
这是我的代码:
function isPrime(n)
{
boolean prime=true;
if(n==1 || n==0)
{
prime= false;
}
if(n==2)
{
prime= true;
}
else
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
prime= false;
}
}
}
return prime;
}
function printPrimes()
{
document.writeln("<textarea rows="10" cols="15">");
for(var i=0; i<=1000; i++)
{
if(isPrime(i)==true)
{
document.writeln("<p>" + i + "</p>");
}
}
document.writeln("</textarea>");
}
printPrimes();
这是我的html:
<!DOCTYPE html>
<html>
<head>
<script src="prime.js" type="text/javascript"> </script>
</head>
<body>
<h1> Prime numbers between 1 and 1000 are: </h1>
</body>
当我在chrome上打开html文件时,仅标题显示脚本似乎没有运行!
When i open the html file on chrome only the header shows up the script doesnt seem to run!
推荐答案
您正在将脚本导入< head>
中,因此将在其中输出脚本.尝试将其移动到< body>
.
You're importing the script in the <head>
, so that's where it's output will go. Try moving it to the <body>
.
这可能是查找质数的最慢方法.
That's possibly the slowest way to find primes.
edit —另一个问题是:
edit — another problem is this:
for(int i=2;i<n;i++)
JavaScript中没有 int
关键字-它是 var
.这将导致语法错误,该错误将显示在错误控制台中.也没有 boolean
关键字("prime"的声明).在进行任何HTML/JavaScript开发时,保持错误控制台打开很重要.
There is no int
keyword in JavaScript - it's var
. That would cause a syntax error, which would show up in the error console. Neither is there a boolean
keyword (declaration of "prime"). It's important to keep the error console open while doing any HTML/JavaScript development.
这篇关于我在没有任何用户操作的情况下显示javascript输出时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!