How to find prime numbers in entered number range [duplicate] - javascript

This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I'm just trying to find prime numbers of an entered range of numbers. I have no clue how to calculate finding primes. I need to add them to an array and output the array after. I put a placeholder for the calculation... I just can't seem to figure out how find the primes.
<!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>

try this full page of prime no example
<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>

You should use some algorithm to check whether a given no is prime no or not inside while loop .
http://en.wikipedia.org/wiki/Prime_number
http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_Algorithms

You need two loops here - the first to run between beginNum and endNum and the second to run from 1 to beginNum for each value of beginNum in the outer loop.
Try replacing the main section of your code with the following. (For clarity, I'm going to introduce a new variable - numberBeingTested.)
var ctr = 0;
var numberBeingTested = beginNum;
while (numberBeingTested <= endNum){ //throwaway
var testDivisor = 2;
var isPrime = true;
while (testDivisor < numberBeingTested ){ //throwaway
if (numberBeingTested % testDivisor == 0) {
isPrime = false;
}
++testDivisor;
}
if (isPrime){
primeNumbs[ctr] = numberBeingTested;
++ctr;
}
++numberBeingTested;
}
Note that there are many possible improvements here - for a start, this code as it stands will tell you that 1 is prime, and there are significant possible performance improvements (such as testing possible divisors up to the square root of the number being tested rather than the number itself) - but for your purposes it will probably suffice.

What I try was to edit Sieve of Atkin algorithm from linked question:
function getPrimes(min, max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
if (i >= min) {
primes.push(i);
}
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
console.log(getPrimes(10, 100));
This will give you array with prime numbers from min to max. It still has to go through all number from 2, so maybe there will be more effective way how to achieve this.

Related

If statement with OR condition not working

I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>

How can I get value from user for click function using if statement for a password generator?

I'm very new to JavaScript so forgive me if the code is wrong. I have a problem getting a value from the user when the value is a number or letter.
If it is a number the function should execute, but if it is not a number it should display an alert telling the user to input a valid number.
Well, my application displays the alert when the user entry is both a letter and/or a number. Any help would be greatly appreciated.
I have tried using an if statement which will be shown in the code below under the Generate click function.
Edited to include HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Password Generator</title>
<link rel="stylesheet" href="password.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="password.js"></script>
</head>
<body>
<main>
<h1>Password Generator</h1>
<h2>Generate a strong password</h2>
<label for="num">Number of characters:</label>
<input type="text" id="num"><br>
<label for="password">Password:</label>
<input type="text" id="password" disabled><br>
<label> </label>
<input type="button" id="generate" value="Get Password">
<input type="button" id="clear" value="Clear"><br>
</main>
</body>
</html>
"use strict";
$(document).ready(function() {
var getRandomNumber = function(max) {
for (var x = 0; x < length; x++) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
}
return random;
};
$("#generate").click(function() {
$("#password").val(""); // clear previous entry
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+!#";
var num;
if (num >= 0 && num <= 100) {
//If the user entry is valid, the function will execute and return password
return num;
//If user entry isn't a valid number, display alert
} else if (isNaN(num)) {
alert(" Please enter a valid number ");
}
}); // end click()
$("#clear").click(function() {
$("#num").val("");
$("#password").val("");
$("#num").focus();
}); // end click()
// set focus on initial load
$("#num").focus();
}); // end ready()
Please provide html part.
and when you click #generate, you didn't define the value of num variable.
Change this line and try again
var num= $("#num").val();
You should get the user input to a variable and validate that
var num = $("#password").val(""); // clear previous entry
if (isNaN(num)) {
return alert(" Please enter a valid number ");
}
else {
if (num >= 0 && num <= 100) {
return num;
else
// ..... return another error message here
}

Random number generation/shuffling issue

Okay so, I'm trying to create an application where when you click a button it Generates and Displays a concatenated sequence of unique Numbers between 1 and 76. I have it generating 1 -78 randomly with no dupes but I am unsure as to how I would make it so when it comes to displaying it, it displays 1 number and then increments +1 with every click.
So first click [28]
second click [28, 33] and so on without duplicates. here is the code I have so far
window.onload = onclick;
function onclick() {
document.getElementById("BtnCall").onmousedown = GenNumber;
}
function GenNumber() {
var num = LoadNumbers(1, 76);
num = shufflearray(num);
for (i = 0; i < 1; i++) {
ShowArray(num);
}
};
function LoadNumbers(min, max) {
var arr = [];
for (var i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
function shufflearray(input) {
var out = [];
while (input.length > 0) {
var i = Math.random() * input.length;
var a = input.splice(i, 1);
out.push(a);
}
return out;
}
function ShowArray(m) {
for (var i = 0; i < m.length; i++) {
document.getElementById("usednum").innerHTML += (m[i]+', ');
}
}
Thanks for any support/help :)
needs to behave/like this
https://gyazo.com/bebb7c58c402934050be8bc9be29e183
instead of this:
This happens with one single click
I think you're making random number concatenation one after another logic TOO complicated with your existing code like GenNumber(), LoadNumbers() and shufflearray() method. I just post an example answer that will fulfill what you want to do as per "Need to behave like this" (If I were you then I'll try this way).
By the way I've also posted an answer with your existing code also.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Generate Random Number</title>
</head>
<body>
<p id="show_random"></p>
<script type="text/javascript">
var randoms = [];
function makeid() {
var randomnumber = Math.ceil(Math.random() * 76);
randoms.push(randomnumber);
//console.log(randoms);
document.getElementById('show_random').innerHTML = randoms.join(' ');
}
</script>
<input type="button" style="font-size:9pt" value="Gen Random" onclick="makeid()">
</input>
</form>
</body>
</html>
See it with your code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Generate Random Number</title>
</head>
<body>
<p id="usednum"></p>
<script type="text/javascript">
window.onload = onclick;
function onclick() {
document.getElementById("BtnCall").onmousedown = GenNumber;
}
function GenNumber() {
var num = LoadNumbers(1, 76);
num = shufflearray(num);
var single = Math.ceil(Math.random() * num.length);
ShowArray(single); //with you existing code you're passing whole array
};
function LoadNumbers(min, max) {
var arr = [];
for (var i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
function shufflearray(input) {
var out = [];
while (input.length > 0) {
var i = Math.random() * input.length;
var a = input.splice(i, 1);
out.push(a);
}
return out;
}
function ShowArray(m) {
document.getElementById("usednum").innerHTML += (m + ', ');
}
</script>
<input type="button" style="font-size:9pt" value="Gen Random" id="BtnCall">
</input>
</form>
</body>
</html>

What's wrong in this simple javascript code?

I want to make a program which can sum up all the digits in a given number. I want my script to return the resul on click of the button Please help me find error in my code. Thanks
<!doctype html>
<html>
<head>
<script type="text/javascript">
function sumdigits()
{
var num=document.getElementById("a").value;
var len=num.length();
alert(len);
if(len!=0)
{
var sum=0;
var ldigit=0;
while(num!=0)
{
ldigit=num%10;
sum+=ldigit;
num/=10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number="+sum;
}
</script>
</head>
<body>
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</body>
</html>
DEMO
onClick should be onclick, length() should be length and sum not out of scope
function sumdigits(){
var num = document.getElementById("a").value;
var len = num.length; // note "length"
var sum; // "sum" scope
alert(len);
if(len!==0){
sum = 0;
var ldigit=0;
while(num!==0){
ldigit=num%10;
sum += ldigit;
num /= 10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number = "+ sum;
}
This is how to make it work, now, I don't know what math you're trying to apply in there and what's it's purpose...
The main reason the script is breaking is because you are calling length() on num variable instead of num.length. Below is a link to a working fiddle with that and a few other adjustments made ( check to see if the value's are integers etc...).
http://jsbin.com/uBAyOJep/1/
<!doctype html>
<html>
<head>
</head>
<body>
<form onsubmit="sumdigits()">
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</form>
</body>
</html>
function sumdigits()
{
var sum = 0,
num = document.getElementById("a").value,
len = num.length,
result = document.getElementById("result");
if( len !== 0 ){
for( var i = 0; i < len; i++){
var lineValue = parseInt(num[i], 0);
if ( !isNaN(lineValue) ) {
sum += lineValue;
}
}
}
result.innerHTML="Sum of digits of the given numbers = " + sum;
}

Prototype issue - How do I check for links on an input field and check for the length of that input field?

I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0

Categories