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) 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.
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>.
This is my code:
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();
This is My 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>
When i open the html file on chrome only the header shows up the script doesnt seem to run!
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 — another problem is this:
for(int i=2;i<n;i++)
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.
This is because you are attempting to write the <textarea> to the <head> element. Try loading/executing your script within the <body>.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have been trying to get this code to work, my assignment is to create a javascript where the user inputs a letter grade then it gives them an alert of what kind of grade they are gonna get. For some odd reason, I cant get the alert working. My teachers example involves using a function but I dont know what to put in there.
<html>
<head>
<script>
Function(){
var x = document.getElementById("score").value;
if x >=1: {
alert("invalid grade")
}
if .99>= x >=.9: {
alert("A");
}
if .89>=x>=.8:{
alert("B");
}
if .79>=x >=.7:{
alert("C");
}
if .69>=x >=.6:Z{
alert("D");
}
if x<=.59:{
alert("F");
}
{
</script>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button onclick=print("x")">click</button
<body>
</html>
See all the comments below:
<html>
<head>
</head>
<body>
<p>Enter Score in the box:</p>
<input type="text" id="score">
<button>click</button>
<!-- Your script should be just before the closing body tag
so that by the time the browser reaches it, all the HTML
will have been read into memory. Your teacher isn't really
showing you the most correct technique if he/she told you
to put it in the HEAD section. -->
<script>
// Set up event handling in JavaScript, not in HTML. Your teacher is wrong
// to teach you that way. First, find the right HTML element, then configure
// it for the event and the function to call when the event occurs.
document.querySelector("button").addEventListener("click", showGrade);
// JavaScript is case-sensitive. Functions use the word "function" (lower case)
// and, in this case, need a name (that you can make up) to be able to call it later.
function showGrade(){
var x = document.getElementById("score").value;
// The condition for an "if" must be in parenthesis
// and when there are multiple parts to the conditon
// you have to use AND (&&) or OR (||) operators and
// each part must be a complete condition on its own.
// Also, the colons you had were incorrect syntax.
// Lastly, because a grade will be only one of your
// choices, you should use "else if" on the second and
// subsequent tests, so that if the first test fails,
// each of the next ones will run. But, once you've
// ruled out all the possiblilites except for one (the
// last one), you don't need to test and just use "else".
// For example, if the grade isn't and A,B,C, or D, it
// must be an F.
if (x >=1 ){
alert("invalid grade")
} else if (x >= .9 && x <= .99) {
alert("A");
} else if (x >= .8 && x <= .89) {
alert("B");
} else if (x >= .7 && x <=.79) {
alert("C");
} else if (x >= .6 && x <= .69) {
alert("D");
} else {
alert("F");
}
}
</script>
</body>
</html>
More reading:
Using .addEventListener() to set up event handlers
Finding elements in the document with .querySelector()
Writing an if...else/if statement
I am total beginner (1 week learning this ...and already thinking about quitting before getting crazy :D) and this is my first question, so please, if I do something wrong, just let me know.
I am trying to solve a small Javascript exercise about adding a list to a HTML file with a JS function.
I have created this function, but It is not working. I would say the problem is that I don't know how to indicate the bands name variable inside the ".createTextNode()" .
This is the function I have in a JS file :
function addBands() {
for (i = 0, i < 0, i++) {
var banda = document.createElement("LI");
var nombre= document.createTextNode([0]);
banda.appendChild(nombre);
document.getElementById("band-list").appendChild(banda)
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1> MY FAVORITE BANDS</h1>
<ul id="band-list">
</ul>
<script src="exercisesJS.js"></script>
<script>addBands(['Dire Straits', 'Kansas', 'Steely Dan'])</script>
</body>
</html>
The output should be a list with the name of the 3 bands in the Function, or any other bands (could be 3, or 6 ...etc...
Always check the error console. It's currently telling you that
for (i = 0, i < 0, i++) {
is a syntax error. You mean:
for (i = 0; i < 0; i++) {
That fixes the syntax. However that's still logically wrong, since it means your loop will never run (since the iterator variable i starts at 0, and is told to run while it is under 0, a condition it fails right from the beginning.)
Looking at your code, there's other problems. You're passing an array of band names to the function, but the function isn't set up to receive it. So, we need:
function addBands(bands) {
That means the inner part of the function can access what was passed to it. It also means we can base our loop on the number of bands that were passed, and use the iterator band as the textual output.
function addBands(bands) { //<-- receive incoming array
for (i = 0; i < bands.length; i++) { //iterate bands.length times
var banda = document.createElement("LI");
var nombre= document.createTextNode(bands[i]); //output iterator band name
banda.appendChild(nombre);
document.getElementById("band-list").appendChild(banda)
}
}
While we're here, there's a couple of other optimisations we can make. Firstly, there's no sense in freshly looking up the ul element each time the loop runs. So let's cache it outside the loop. Secondly, while createTextNode() is fine, you may be interested to know that it's easier to just use textContent on the parent node. Putting it all together:
function addBands(bands) { //<-- receive incoming array
let ul = document.getElementById("band-list"); //cache UL
for (i = 0; i < bands.length; i++) {
var banda = document.createElement("LI");
banda.textContent = bands[i];
ul.appendChild(banda)
}
}
Refer to #Utkanos's answer to exactly understand what went wrong in your code. Given that, I suggest the following solution, which uses ES2015 .forEach method of arrays, for looping over your provided list.
function addBands(liArray) {
liArray.forEach(liText => {
const li = document.createElement('li')
const liTextNode = document.createTextNode(liText)
li.appendChild(liTextNode)
document.getElementById("band-list").appendChild(li)
})
}
addBands(['Dire Straits', 'Kansas', 'Steely Dan'])
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1> MY FAVORITE BANDS</h1>
<ul id="band-list">
</ul>
<script></script>
</body>
</html>
I've got a webpage which is meant to generate a random number, then when the number =5 it displays a win message..if not display lose message, but its not displaying any alerts..have i missed something out?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
return x;
if (x=4)
{
alert("winner!");
}
else
{
alert("loser");
}
}
</script>
</head>
<body>
<p id="demo">Click the button to display a random number between 1 and5.</p>
<button onclick="WinLose()">Try it</button>
</body>
</html>
EDIT:
Managed to get this bit working so now it displays either win or loose depending on its number, yet does anyone know how i can swap the alerts in the if statements to display a DIV section. ive got a jQuery file included so it can accept the hide/show effect...anything i tried didnt work
you have return x after you generate a random value for x. this means no javascript code after that line will run in that function.
also, your if statement needs to use '==' to do the comparison rather than '=' which is assignment.
Yeah, It can be tough. The main problem again has to be other than return x is the "==". So this
if (x=4)
Should really say:
if (x==4)
What you said before was that you were assinging x to 4 so that has no meaning at all and messes everything up.
Hope this helps you!
You need to return x after you generate the random value; and you must add x == 4
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
if (x==4) {
alert("winner!");
} else {
alert("loser");
}
return x;
}
DEMO
Your code:
x=x.innerHTML=Math.floor((Math.random()*5)+1);
x is receiving x.innerHTML then x.innerHTML = random number.
Correct way: (remove "x=")
x.innerHTML = Math.floor((Math.random()*5)+1);
Here is a simplified version that externalizes the alerts (I assume you don't plan to use them later)
function WinLose(){
var x=Math.floor((Math.random()*5)+1);
document.getElementById("demo").innerHTML=x;
return (x==5) ? "Winner!" : "Loser";
}
alert(WinLose());
I have this code in a php file on my web server and it is being displayed through a VB.NET program using the "web browser", and seeing some people still use IE as their default web browser they are getting this error every time they launch the program. Anyone have any idea what might be causing this?
<SCRIPT TYPE="TEXT/JAVASCRIPT">
function Toggle(image, list)
{
var listElementStyle = document.getElementById(list).style;
if (listElementStyle.display == "none")
{
listElementStyle.display = "block";
document.getElementById(image).src="./images/minus.png";
document.getElementById(image).alt="Close";
}
else
{
listElementStyle.display="none";
document.getElementById(image).src="./images/plus.png";
document.getElementById(image).alt="Open";
}
}
function TreeInit(nodes)
{
var counter;
for( counter = 1; counter <= nodes; counter++ )
{
document.getElementById('childList' + counter).style.display="none";
}
}
</SCRIPT>
TreeInit is called later at the bottom of my webpage.
<SCRIPT TYPE="TEXT/JAVASCRIPT">
TreeInit(4)
</SCRIPT>
I've added a ; after TreeInit(4)
The error was that I only had two children, not 4. Changed TreeInit(4); to TreeInit(2); and all is well. Thank you all for your help!
Made sure I had the correct number of child lists, now the errors have vanished.
I am trying to make each number displayed clickable. "1" should alert() 80, "2" should produce 60, etc.
However, when the alert(adjust) is called, it only shows 0, not the correct numbers. However, if the commented out alert(adjust) is uncommented, it produces the correct number on page load, but not on clicking.
I was wondering why the code inside addEvents cannot access the previously defined variable adjust.
<html>
<head>
<script type="text/javascript" charset="utf-8" src="mootools.js"></script>
<script type="text/javascript" charset="utf-8">
window.addEvent('domready', function() {
var id_numbers = [1,2,3,4,5];
for(var i = 0; i<id_numbers.length; i++) {
var adjust = (20 * (5 - id_numbers[i]));
// alert(adjust);
$('i_' + id_numbers[i]).addEvents({
'click': function() {
alert(adjust);
}
});
}
});
</script>
</head>
<body>
<div id="i_1">1</div>
<div id="i_2">2</div>
<div id="i_3">3</div>
<div id="i_4">4</div>
<div id="i_5">5</div>
</body>
</html>
Thanks.
You are having a very common closure problem in that for loop.
Variables enclosed in a closure share the same single environment, so by the time the click callbacks are called, the for loop would have run its course, and the adjust variable will be left pointing to the last value it was assigned.
You can solve this with even more closures, using a function factory:
function makeClickHandler(adjust) {
return function() {
alert(adjust);
};
}
// ...
for(var i = 0; i<id_numbers.length; i++) {
var adjust = (20 * (5 - id_numbers[i]));
$('i_' + id_numbers[i]).addEvents({
'click': makeClickHandler(adjust)
});
}
This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:
Mozilla Dev Center: Working with Closures