JavaScript Prime Number Generator - javascript

I'm trying to write a JavaScript prime number generator that lists every prime between 1 and 100. I know this is a common programming exercise and there's an abundance of solutions on the web. My question is why does my solution result an empty array? Here's the code:
var primeNumbers = [];
for (var x=2; x<101; x++)
if (x%2 === 0)
{
break;
}
else
{
for (var y=2; y<101; y++)
{
if (x/y > 1)
{
break;
}
else
{
primeNumbers.push(x);
}
}
}
};
console.log(primeNumbers);

Because the first thing you do is break if x % 2 === 0. Which is true immediately. break will exit the loop. I think you want continue.

Problem 1: You break when x%2 === 0, so you exit the loop at once. Reverse the condition and enter the code in the loop directly:
Replace this:
if (x%2 === 0) {
break;
}
else {
with:
if (x%2 !== 0) {
Problem 2: You are exiting the inner loop if x/y > 1. This is the same as the condition x > y, so that will always exit the inner loop immediately. Instead make the inner loop run from two and up to one less than x:
for (var y=2; y<x; y++) {
Problem 3: Instead of dividing x by y and comparing to one, you should use the modulo operator: x%y. If the result is zero, then x is not a prime number.
Problem 4: You are adding prime numbers inside the inner loop, so you will end up with most numbers multiple times, not just prime numbers once.
You need to add a variable to keep track of what's happening in the inner loop. If none of the checks in the inner loop are zero, then you can add x to the list of prime numbers.

You don't have to test every number before the limit, you just have to test the prime numbers you found before that number.
If you were looking to find all prime numbers between 1 and 10, when you are testing 7 for example you should test
7%2 === 0 false
7%3 === 0 false
7%5 === 0 false
than 7 is a prime number and your prime number array should be
[0,1,2,3,5,7]
and as you see I didn't test 4 because 4 isn't a prime number. This are the numbers you will test 8
8%2 === 0 true > return false
and you don't have to test more because you already know it isn't a prime number. So the final solution should be like
function getPrimes(x){
var ar = [];
for (var counter = 0; counter <= x; counter++) {
var notPrime = false;
for (var i = 2; i <= ar.length && !notPrime; i++) {
if (counter%ar[i]===0) {
notPrime = true;
}
}
if (notPrime === false) ar.push(counter);
}
console.log(ar)
}
getPrimes(250);

var funPrimeNumber=function(val){
var iniX=2;
var iniY=2;
var flag=1;
while(iniX<val){
iniY=2;
flag=1;
while(iniY<iniX){
if(iniX%iniY==0){
//NOT PRIME NUMBER
flag=0;
}
iniY++;
}
if(flag==1){
//PRIME NUMBER
document.write(iniX + ", ");
}
iniX++;
}
}
funPrimeNumber(100);

Related

Why is unshift() returning a different value than push() if I am targeting the first element in the former and the last element in the latter?

I have a function for Project Euler #7. Towards the end, I changed the code from primeArray.push(i); to primeArray.unshift(i) and return primeArray[primeArray.length - 1]; to return primeArray[0];. This altered the return. In the former. It returned the correct answer, 104021, while the latter returned 20001, which is not even prime. I do not understand why that is.
function primeFinder(primeTarget) {
//since 2 is the only even prime, putting it here saves us some effort in checking primality by just iterating over the odd numbers
//it also helps the for loop since we are only interested in checking for divisors among previous primes.
let primeArray = [2];
let i = 3;
while (primeArray.length < primeTarget) {
let primeLogger = false;
//We don't need to check for divisibility by 2, so j can equal 1
for (j = 1; j < primeArray.length && primeArray[j] < Math.sqrt(i); j++) {
if (i % primeArray[j] === 0) {
primeLogger = true;
//Since we have found a divisor and changed primeLogger, we can exit the loop
break;
}
}
//Where the break goes to, and also where the for loop goes to once finishes
if (primeLogger === false) {
primeArray.push(i);
}
i += 2;
}
return primeArray[primeArray.length - 1];
}
console.log(primeFinder(10001));
Because primeArray is now in descending order but your loop still searches from start to end; now from biggest towards smaller values. Until it finds something that is >= Math.sqrt(i) which most likely will be the very first check, j=1.
Then it ends the loop with primeLogger === false
so for example, for:
i=9, j=1
primeArray === [7,5,3,2]
primeArray[j] === 5
And since the check 5 < Math.sqrt(9) is false the loop is finished.
Therefore 9 is a prime number and is now added to the start of primeArray.

What does this code do? im trying to learn some for loop with modulo

this is only a part of the code
What does this loop do? This is a JavaScript for loop I'm trying to learn some JavaScript with modulo in it but I can't understand this one.
for (var x = 2; x < n; x++) {
if (n % x === 0) {
return false;
}
}
return true;
}
}
The above code will increment x (starting at 2) until it's 1 less than n. Each iteration, it checks if "n" can be evenly divided by "x". (Modulos are used to find the remainder). If it is evenly divisible, the program return false.
This code is a prime number checker. If it gets to the bottom it means "n" can only be divided by itself and returns true.

Why does the following javascript cause Unresponsive Script error?

When trying out the code below as a solution for the Euler Project problem 5. The problem is find the smallest number equally divisible by all numbers from 1 to 20. Every time it is run it presents "Unresponsive Script" window and I need to physically stop the script from running. It seems like something is causing it to hang but I can't quite figure out what. The alert window seems to point to an error with the line the while() starts on but I can't see anything wrong with it.If it looks like it should work I'd appreciate anyone trying it on their machine to see if it works. That way I can eliminate it as a local problem. All suggestions welcome.
var divisible = false;
var n = 2520; // first number divisible by all numbers 1-10
while(divisible === false){ // something wrong here??
n += 2520;
for(var i = 11; i < n; i++) {
if(i % n !== 0){
break;
}
if(i === 20) {
divisible === true;
}
}
}
if(divisible === true){
return console.log("Answer: " +i);
}
Because you break out of your for loop if i % n isn't 0 the very first time. And you never set divisible to true - divisible === true isn't the same as divisible = true
There are several errors in the original code, some pointed out in the answer above. To make it work several fixes are needed.
First, the boolean divisible must be correctly set to true using the assignment operator = inside the for loop instead of === which is used only to check if two values are strictly of the same type AND value.
The next problem is the conditional part of the for loop i < n should be i < 20 because the loop is checking if numbers between 11 and 20 divide evenly into n.The last fix to make the code run correctly is the order of the condition if the first if statement which should read if(n % i !== 0) and not if(i % n !== 0). I think it might be this specific part that caused the code to crash and generate the "Unresponsive Script" alert in the browser.
Here is the fixed code.
var divisible = false;
var n = 2520; // smallest number divisible by all numbers 1-10
while(divisible === false){
n += 2520; // increment n on each new pass
// loop numbers between 11 and 20
for(var i = 11; i <= 20; i++) {
if(n % i !== 0){ // check if i divides equally into n
// if not break out of current loop and start again
break;
}
// if i reaches 20 then all the numbers divided equally into n
if(i === 20) {
// set value of divisible to true to cancel while loop
divisible = true;
}
}
}
// return the last value of n
return console.log("Answer: " +n);

Massive for loop taking too long to load

I'm working on a program designed to generate prime numbers, and I'm trying to find the 10001st prime number. Each time the loop runs, it tests variable i to see if it's divisible by variable j, which is part of another loop that goes up to half of i. If i is divisible by j then it adds one to variable prime, and when the loop's done it checks to see if variable prime is larger than two; if it is, then i is not prime. If it is prime, it gets push()ed to the variable array, which stores all the primes. Sorry if that's a little confusing.
My problem is that although this code works, whenever I set the first for loop too high (here I have it end at 100000), my browser freezes:
var prime = 0;
var array = [];
for(var i = 2; i <= 100000; i+=1) {
var prime = 0;
for(var j = 0; j <= i/2; j+=1) {
if(i % j === 0) {
prime += 1;
}
}
if(prime < 2) {
array.push(i);
}
}
console.log(array.length)
I know I could just copy and paste all the prime numbers but I want to make the program work. Any ideas to make the program stop freezing?
This is because the time complexity of your algorithm is pretty much O(n^2). Sieve of Eratosthenes created a better algorithm that will prevent your browser from freezing.
Here is one way of doing it:
var exceptions = {
2: 2,
3: 3,
5: 5,
7: 7
}
var primeSieve = function (start, end) {
var result = [];
for (start; start < end; start++) {
if (start in exceptions) result.push(start);
if (start > 1 && start % 2 !== 0 && start % 3 !== 0 && start % 5 !== 0 && start % 7 !== 0) {
result.push(start);
}
}
return result;
};
You can obviously make this look prettier, but I just did it quickly so you can get the point. I hope this helps! Let me know if you have further questions.

What is the mistake in my code? Computing prime numbers upto n

function primesuntil(n) {
var primes = [2];
for (i=3; i < n ; i++) {
var j=0;
while (j<primes.length) {
var quotient = i/primes[j];
if (quotient !== math.floor(quotient) {
var hasDivisor = false;
j++;
}
else {
var hasDivisor = true;
j=primes.length+15;
}
}
if (hasDivisor == false)
{primes.push(i);}
else
{var nothing = 3;}
}
printarray(primes);
}
I want to run this code in JavaScript, which is supposed to print all prime numbers smaller than n, but for some reason it will not run. Have I made a mistake somewhere? When i comment this function out the rest of the code does run.
What the code should do is divide all numbers in the array "primes", and if at some point the quotient equals the 'floor' of that number (meaning it is divisable by the number from the array), hasdivisor becomes true and the number is not added to the array of primes. also, j stops counting (we don't have to divide by the other primes anymore, we know it's not prime). If it doesn't divide any prime numbers smaller than itself, it is prime, so it is added to the list. What's wrong?
It is if (quotient !== math.floor(quotient)) an extra ), and it is Math.floor, uppercase M.
You have a missing closing parentheses in this line :
if (quotient !== math.floor(quotient)) {

Categories