JavaScript - Help With Printing Prime Numbers 1-100
I have the following code attached that gives me a prime number. I can't seem to put the logic behind having this code print from an alert the prime numbers from 1-100. Of course, this code is only giving me "the" prime number. I just don't know where to begin, or how to store each number. Array maybe?
Code:
var finding_primes = function() { var number = 31, prime = true; for ( var i = 2; i < number; i++ ) { if ( number % i == 0 ) prime = false; } if (prime) { alert( number + " is prime."); } else { alert( number + " is not prime."); } } Similar TutorialsI would like to create a script that allows for a user to input two integers and to have the script show all the prime numbers that fall between them. Any thoughts? Thanks i am using trying to use the following code to find the prime factors of a number: Code: function prime(number){//returns prime factors of input in array test=2;//number to test divisibility factor_count=0//counts number of factors factors=[]; while (test<number){ quotiant=number/test quotiant_round=Math.floor(quotiant); if(quotiant==quotiant_round){//number is divisible by test factor_count=factor_count+1; factors[factor_count]=test; number=number/test; test=test-1;//counters adding one } test=test+1; } return (factors) } running it manually in chromes JavaScript console i get: prime(2)=[] prime(4)=[undefined, 2] prime(8)=[undefined, 2, 2] prime(6)=[undefined, 2] prime(9)=[undefined, 3] prime(27)=[undefined, 3, 3] prime(18)=[undefined, 2, 3] i am using the = to separator my input from its output Hi there everyone, My question is one that has been asked many times before always with the same answer. I'm hoping that all the new developments with JQUERY and Prototype that a method would have come about on how to print an external HTML file without first opening it? So you click it and it prints without having to use frames, redirects etc... Any ideas? Hi I have the code below which geocodes a postcode and returns a lat a long value. Its standard code from Google maps. I just want to print these values to a screen. I tried document.write(value) but this produces nothing. Any help would be greatly appreciated. Code: <script type="text/javascript"> var localSearch = new GlocalSearch(); function usePointFromPostcode(postcode) { localSearch.setSearchCompleteCallback(null, function() { if (localSearch.results[0]) { var resultLat = localSearch.results[0].lat; var resultLng = localSearch.results[0].lng; } document.write(resultLat+resultLng); //alert("Latitude: " + resultLat + "\nLongitude: " + resultLng + " q"); }); localSearch.execute(postcode + ", UK"); } </script> TIA Stew Quote: var c739=new Array ("C#739","Brick Township","125 Route 65","Brick","NJ","08723","Phone #","1234569"); Quote: var c741=new Array ("C#741","Brick","125 kool st ","copolla","NJ","07831","Phone #","6957891"); Quote: document.write(c739[1]); I need help for the above code. I created a simple Array which would then be growing too soon. I need to add a prompt : store : c739 then all the elements would show as: C#739 Brick Township 125 Route 65 Brick, NJ 07831 Phone# 1234569 Please help. Thank you in advance. I have a routine that prints a textarea: Code: function printInput(f){ var ifr = window.frames['printFrame']; if (ifr){ //print the content of the invisible iframe ifr.document.getElementById('content').innerHTML=f.WRKNOTEPAD.value.replace(/\n/g,'<br />'); ifr.focus(); ifr.print(); } else { //print by opening a new window and then closing it var html='<html><head><style type="text/css">div{font:normal 14px Verdana}</style></head><body onload="window.print();window.close()"><div>'+f.WRKNOTEPAD.value.replace(/\n/g,'<br />');+'</div></body></html>' var win = window.open('','_blank','menubar,scrollbars,resizable'); win.document.open(); win.document.write(html); win.document.close(); } } function writeContent(objIframe){ var html='<html><head><style type="text/css">div{font:normal 14px Verdana}</style></head><body><div id="content"></div></body></html>' objIframe.document.write(html); objIframe.document.close(); } This works nicely when the button is of input type: Code: <form name="FORMNOTES"><textarea name=WRKNOTEPAD cols=140 rows=20 wrap=yes style=\"font-family: Arial; font-size: 10pt\"></textarea><div> <br> <input type="button" value="Print notepad" onClick="printInput(this.form)"> </div> <iframe name="I1" id="printFrame" src="javascript:parent.writeContent(this)" width="1" height="1"></iframe></form> But when I try to make the input button an img button it errors: Code: <img border="0" src="/images/printnotes.gif" onClick="printInput(this.form)"> The error is "WRKNOTEPAD is null or not an object". Is there any way to overcome this and use an image to achieve the same thing? I'm thinking that the image is not an element(?) - is that the reason? Thanks for any light on this. Hey. I have been pulling out my hair trying to do this. I am printing out the contents of a DIV tag but it does not print the css with it. Just the basic text For example: .testDiv { border: 1px solid #0F0; margin-right: 300px; text-decoration: underline; font-weight: bold; } The print does not change the text according to the css. Why is this? Thanks in advance for any help. Marc Hi Guys, Using this code i have managed to get the query value from the url. code: PHP Code: <script type="text/javascript"> // Check referrer function getQuerystring(key, default_) { if (default_==null) default_=""; key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regex = new RegExp("[\\?&]"+key+"=([^&#]*)"); var qs = regex.exec(window.location.href); if(qs == null) return default_; else return qs[1]; } var refVal = getQuerystring('r'); </script> <div id="div-regForm"> <div class="form-title">Sign Up</div> <div class="form-sub-title">Earn points & then swap for prizes! FREE!</div> <form id="regForm" action="sign-up.php" method="post"> <table> <tbody> <tr> <td><label for="fname">First Name:</label></td> <td><div class="input-container"><input name="fname" id="fname" type="text" value="<?php print $_POST['fname']; ?>" /></div></td> </tr> <tr> <td><label for="lname">Last Name:</label></td> <td><div class="input-container"><input name="lname" id="lname" type="text" value="<?php print $_POST['lname']; ?>" /></div></td> </tr> <tr> <td><label for="email">Your Email:</label></td> <td><div class="input-container"><input name="email" id="email" type="text" value="<?php print $_POST['email']; ?>" /></div></td> </tr> <tr> <td><label for="pass">Password:</label></td> <td><div class="input-container"><input name="pass1" id="pass1" type="password" value="<?php print $_POST['pass1']; ?>" /></div></td> </tr> <tr> <td><label for="pass">Confirm Password:</label></td> <td><div class="input-container"><input name="pass2" id="pass2" type="password" value="<?php print $_POST['pass2']; ?>" /></div></td> </tr> <tr> <td><label for="cntry">Country:</label></td> <td><div class="input-container"><select name="cntry"><?php foreach($countryArray as $country) { print "<option value=\"$country\">$country</option>"; } ?></select></div></td> </tr> <tr> <td> </td> <td><input name="r" type="hidden" value="<script type="text/javascript">document.write(refVal);</script>" /><input type="submit" class="greenButton" name="submitSignUp" value="Sign Up" /></td> </tr> </tbody> </table> </form> </div> in this part value="<script type="text/javascript">document.write(refVal);</script>" /> i can't seem to put the value in the hidden field it print fine in the code just above. thanks for any help guys Graham Hello. Im trying to put in a Popup printer-friendly page on my site. the Popup works great in Chrome and FireFox. It even works in IE - except im getting a black bg instead of the white i get in the other browsers. Also the print command is not working in Firefox or IE. Im running FireFox 8 and IE 9. heres the code for the Popup: Code: <script language="javascript" type="text/javascript"> <!-- function popitup(url) { newwindow=window.open(url,'name','height=200,width=150'); if (window.focus) {newwindow.focus()} return false; } // --> </script> </head> <div> <img src="IMAGES/BidsCouponSmall-text.png" /> <br /> <br /> <a href="printcoupon.htm" target="coupon" onclick="window.open('printcoupon.htm','coupon','height=500, width=400,toolbar=no,directories=no,status=no, menubar=no,scrollbars=no,resizable=no'); return false;" >Click HERE To Print</a> <br /> </div> To avoid cluttering of this post, the page im having printing problems with can be found he http://bidsservice.net/printcoupon.htm its all html, css, and JS. no server-side code. When I use the following script in my web page I do not get a print out. Can anyone tell me what is wrong? <!-- Begin // Get today's current date. var now = new Date(); // Array list of days. var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); // Array list of months. var months = new Array('January','February','March','April','May','June','July','August','September','October','Novem ber','December'); // Calculate the number of the current day in the week. var date = ((now.getDate()<10) ? "0" : "")+ now.getDate(); // Calculate four digit year. function fourdigits(number) { return (number < 1000) ? number + 1900 : number; } // Join it all together today = days[now.getDay()] + ", " + months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear())) ; // Print out the data. document.write(today); // End --> Hey there, I've scrollable screen. I'm having a print button on it and "window.print()" function is called on its onclick event. My problem is it only prints the "viewable" part of the screen, not the whole screen. P.S. I'm using IE7 and it must work for IE7 atleast (for rest I'm not bothered). Thanks in anticipation. Hi, I'm using window.print() to print a document. This is the coding : <th colspan="2" align="right"><a href="JavaScript:window.print();" onclick="return verify()"><img src="image/image.gif" width="25" height="20" /></a></th> How can i print the document without printing together the image? Or is there any other way that you guys know? Thanks I'm trying to display a random message by making an array through values in an XML file and then displaying the info on the page. i want to have it so that a new message is generated each time the button is clicked with no repeats. here is what i have Code: function initial() { var xmlDoc; // First option for internet explorer 5 and 6, second option for firefox, internet explorer 7+ window.ActiveXObject ? xmlDoc = new ActiveXObject("Microsoft.XMLDOM") : xmlDoc = document.implementation.createDocument("","",null); xmlDoc.async = false; xmlDoc.load("quotes.xml"); // take the quote and author information from the xml file var pQuotes = xmlDoc.getElementsByTagName('quote'); var pAuthors = xmlDoc.getElementsByTagName('author'); // create arrays var aQuotes = new Array(); var aAuthors = new Array(); // put the quotes into the array for (i=0; i<pQuotes.length; i++) { aQuotes.push(pQuotes[i].childNodes[0].nodeValue); alert(pQuotes); } // put the authors into the array for (i=0; i<pAuthors.length; i++) { aAuthors.push(nAuthors[i].childNodes[0].nodeValue); } // Loop through arrays and print their quotes and authors for (var s in aQuote) { alert(aQuotes[s]); alert(aAuthors[s]); } } var Q = aQuotes.length; var quoteText = document.getElementById('aQuotes'); var authorText = document.getElementById('aAuthors'); var randomquote = Math.floor(Q * Math.random()); function quoter() { var randomquote2 = randomquote; while (randomquote == randomquote2) { randomquote = Math.floor(Q * Math.random()); } document.getElementById('quoteText').innerHTML = aQuotes[randomquote]; document.getElementById('authorText').innerHTML = " - " +aAuthors[randomquote]; quote.innerhtml = aQuotes[randomquote]; author.innerhtml = aAuthor[randomquote]; } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); </script> XML Code: <?xml version="1.0" encoding="utf-8" ?> <quotes> <theQuote> <quote>Over the years your bodies become walking autobiographies, telling friends and strangers alike of the minor and major stresses of your lives.</quote> <author>Marilyn Ferguson</author> </theQuote> <theQuote> <quote>In reality, serendipity accounts for one percent of the blessings we receive in life, work and love. The other 99 percent is due to our efforts.</quote> <author>Peter McWilliams</author> </theQuote> <theQuote> <quote>The secret of joy in work is contained in one word - excellence. To know how to do something well is to enjoy it.</quote> <author>Pearl Buck</author> </theQuote> <theQuote> <quote>The discovery of a new dish does more for human happiness than the discovery of a new star.</quote> <author>Anthelme Brillat-Savarin</author> </theQuote> <theQuote> <quote>When I was born I was so surprised I didn't talk for a year and a half.</quote> <author>Gracie Allen</author> </theQuote> </quotes> HTML Code: <body onload="initial()"> <div id="container"> <div id="header"> <h1>quotes</h1> </div> <div id="content"> <span id="quoteText"></span> <span id="authorText"></span> <br/> <br/> <input type="button" value="Click here for another quote" onclick="quoter()"/> </div> I'm newbie to javascript. I'm trying to print a web part in landscape orientation. I want to include CSS in java script and change the layout of the page. Here is the print code Code: function printWebPart(tagid) { if (tagid) { var html = "<HTML>\n<head>\n"+ $("HEAD").html()+ "\n</head>\n<body >\n"+ $("#"+tagid).html()+ "\n</BODY>\n</HTML>"; var printWP = window.open("","printWebPart"); printWP.document.open(); printWP.document.write(html); printWP.document.close(); printWP.print(); printWP.close(); } } </script> and here is the css class : .landScape { width: 100%; height: 100%; margin: 0% 0% 0% 0%; filter: progid:DXImageTransform.Microsoft.BasicImage(Rotation=3); } Please suggest how do i do this? Hello gurus I have a page that needs to be printed 3 times. Window.Print() is such a great function, but I can't change the default number of pages to 3 with it. Is there anyway to do this? I was thinking maybe if it's a way not showing the print page at all, just printing after the button is hit, I could put it in a loop and print 3 times. Do you guys know of any remedy? Help this poor mortal in here I'm trying to get this code to work in browsers other than IE. It prints the contents of a textarea, say, a notepad, first bringing up the print dialog. It does it with an (almost) invisible iframe. At first I thought it was only for IE, but I must have tested incorrectly (after a few dozen times uploading and printing out you lose your sanity) and I now see that it DOES work in FF, but not in Chrome. For me (and maybe others?) that is very good news because it will probably be easier for someone more knowledgeable than me to solve a Chrome problem rather than an "all other than IE" browsers problem. Code: /* for notepad printouts */ function printInput(f){ var ifr = window.frames['printFrame']; if (ifr){ //print the content of the invisible iframe ifr.document.getElementById('content').innerHTML=f.WRKNOTEPAD.value.replace(/\n/g,'<br />'); ifr.focus(); ifr.print(); } else { //print by opening a new window and then closing it var html='<html><head><style type="text/css">div{font:normal 14px Verdana}</style></head><body onload="window.print();window.close()"><div>'+f.WRKNOTEPAD.value.replace(/\n/g,'<br />');+'</div></body></html>' var win = window.open('','_blank','menubar,scrollbars,resizable'); win.document.open(); win.document.write(html); win.document.close(); } } function writeContent(objIframe){ var html='<html><head><style type="text/css">div{font:normal 14px Verdana}</style></head><body><div id="content"></div></body></html>' objIframe.document.write(html); objIframe.document.close(); } I think this bit: if (ifr) tests for IE and if it fails the condition, it dynamically creates a new window to print from. And I now see it does just this in FF. But not in Chrome. So narrowing it down I think the Chrome failure is in this bit: Code: else { //print by opening a new window and then closing it var html='<html><head><style type="text/css">div{font:normal 14px Verdana}</style></head><body onload="window.print();window.close()"><div>'+f.WRKNOTEPAD.value.replace(/\n/g,'<br />');+'</div></body></html>' var win = window.open('','_blank','menubar,scrollbars,resizable'); win.document.open(); win.document.write(html); win.document.close(); } Is there anyone who can see why this would fall over in Chrome? hi, lets say I have two arrays . The first array has names of fruits and the second array has numbers(1-5) what Iam after is that I try to print fruits names and attach an index number for each ..such as: arr_fruit("apple","melon","banana","grape","...") arr_index(1-5) output should look like... 1-apple 2 apple 3 apple, 4 apple 5 apple 1 melon 2 melon 3melon 4melon 5 melon 1 banana 2 banana ..... ....... so I think ı need a "for looping" and to achieve this but can not figure it out.. thanks. I have written below code to except only number in a textbox. This is working fine. However, When I'm copying and pasting, then it is taking non-numbers. Code: <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <SCRIPT type="text/javascript"> function isNumberKey1(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode = 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </head> <body> Phone number : <input type="text" id="phonenumber" onkeypress="return isNumberKey1(event)" maxlength="10" size="15" > <br /> <br /> Alternative number: <input type="text" onkeypress="return isNumberKey1(event)" id="alt" maxlength="10" size="15"> <input type="button" value="Submit"> </body> </html> Hay! I have a silly question, I have a row of numbers, 1 to 250. The numbers are all in one horizantal line. But I want to use a <br> after every 10 numbers. I tried: if(i % 10) { document.write("<br>"); } This is how I wanted to be: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, Does any one know how can I achieve this I'm still a noob. |