61

In Javascript how would i find prime numbers between 0 - 100? i have thought about it, and i am not sure how to find them. i thought about doing x % x but i found the obvious problem with that. this is what i have so far: but unfortunately it is the worst code ever.

var prime = function (){
var num;
for (num = 0; num < 101; num++){
    if (num % 2 === 0){
        break;
    }
    else if (num % 3 === 0){
        break;
    }
    else if (num % 4=== 0){
        break;
    }
    else if (num % 5 === 0){
        break;
    }
    else if (num % 6 === 0){
        break;
    }
    else if (num % 7 === 0){
        break;
    }
    else if (num % 8 === 0){
        break;
    }
    else if (num % 9 === 0){
        break;
    }
    else if (num % 10 === 0){
        break;
    }
    else if (num % 11 === 0){
        break;
    }
    else if (num % 12 === 0){
        break;
    }
    else {
        return num;
    }
}
};
console.log(prime());
Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
user1599757
  • 653
  • 1
  • 6
  • 3
  • If it can only ever be between 0 and 100, probably best just to find a list of prime numbers and make an array of them. Then, check `indexOf(number) == -1` –  Aug 15 '12 at 09:00
  • 2
    Quick search revealed this great answer http://stackoverflow.com/questions/9138872/finding-sum-of-prime-numbers-under-250 – Peter Aug 15 '12 at 09:03

40 Answers40

88

Here's an example of a sieve implementation in JavaScript:

function getPrimes(max) {
    var sieve = [], i, j, primes = [];
    for (i = 2; i <= max; ++i) {
        if (!sieve[i]) {
            // i has not been marked -- it is prime
            primes.push(i);
            for (j = i << 1; j <= max; j += i) {
                sieve[j] = true;
            }
        }
    }
    return primes;
}

Then getPrimes(100) will return an array of all primes between 2 and 100 (inclusive). Of course, due to memory constraints, you can't use this with large arguments.

A Java implementation would look very similar.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 6
    Nice- could you explain the j for loop? I couldnt find documentation around the "<<" part. – David Gill Jul 06 '13 at 21:17
  • 5
    @BubblewareTechnology - The `<<` operator shifts the left operand left by one bit (after converting it to an integer value if necessary). It's just a quick way to multiply by 2. The inner loop just sets `sieve[j]` to `true` for all multiples of `i`. The reason for doing this is that no multiple of `i` can be prime. – Ted Hopp Jul 07 '13 at 01:56
  • Complexity of your algorithm is more: `O(n^2)`, where as that of **Sieve of Eratosthenes** is `O(n)`. – Om Shankar Oct 16 '14 at 13:35
  • @OmShankar why `n^2`? according to [this answer](http://stackoverflow.com/a/11535121/849891) (and [this comment there](http://stackoverflow.com/questions/11514308/big-o-of-javascript-arrays#comment29207298_11535121)) it should be the usual `n*log log n` (not O(n) btw). – Will Ness Oct 16 '14 at 16:30
  • @OmShankar - Take another look. My code _is_ an implementation of the Sieve of Eratosthenes. While certain improvements are possible (such as starting the inner `j` loop at `i*i` instead of `2*i`), the complexity most certainly is not O(n^2). Also, the complexity of the Sieve of Eratosthenes is O(n log log n), not O(n). – Ted Hopp Oct 18 '14 at 23:41
  • @TedHopp hi Ted, could I know why you rejected my edit? using an array for `sieve` is not optimal – caub Aug 02 '18 at 12:51
  • 3
    @caub - It's a matter of clarity (which, in my opinion, affects maintainability). Declaring `sieve` to be an array signals that values are being stored and retrieved by numerical index. A maintainer (who might wish to modify the code to do other things with `sieve`) will know that `sieve.length` and the array methods are available for use. As to optimality, I'd be surprised if an object performed noticeably better than an array here. In fact, an array may be faster (see [here](https://stackoverflow.com/a/17295727/535871), for instance). – Ted Hopp Aug 02 '18 at 14:59
  • @TedHopp you're right, good to know. I benched "arr" vs "obj" again to make sure, in my answer https://stackoverflow.com/a/33089330/3183756 because JS engines change fast. I thought it would be slower, because arrays has to maintain `.length` – caub Aug 02 '18 at 16:47
62

Here's how I solved it. Rewrote it from Java to JavaScript, so excuse me if there's a syntax error.

function isPrime (n)
{
    if (n < 2) return false;

    /**
     * An integer is prime if it is not divisible by any prime less than or equal to its square root
     **/

    var q = Math.floor(Math.sqrt(n));

    for (var i = 2; i <= q; i++)
    {
        if (n % i == 0)
        {
            return false;
        }
    }

    return true;
}

A number, n, is a prime if it isn't divisible by any other number other than by 1 and itself. Also, it's sufficient to check the numbers [2, sqrt(n)].

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
DavidS
  • 1,660
  • 1
  • 12
  • 26
  • 3
    Instead of `(int) Math.sqrt (n)` use `parseInt(Math.sqrt(n))`, corrected via edit. Using `[abs()](http://www.w3schools.com/jsref/jsref_abs.asp)` negative numbers can be tested too. Also, according to logic, the `if (n < 2)` should return true, since it's a prime number then. – SeinopSys Dec 20 '12 at 19:39
  • Just FYI, this solution is psuedopolynomial. Don't use it unless you know that n will be small. – mihsathe Feb 19 '13 at 08:04
  • FYI, it is the algorithm with the least iterations in this thread. But yes, I agree that the larger the `n` --> find a better one (and win a price money for discovering a new prime :) ) – DavidS Feb 19 '13 at 08:26
  • 2
    seems to work even when n = 10,000,000, not sure what "small" is haha – devonj Feb 19 '16 at 00:05
  • 1
    @devonJS when n=10,000,000 it would stop at the first iteration since it's divisible by 2, it it would be very fast to find out that 10,000,000 is not prime. Nonetheless it can find 2,147,483,647 quite fast as well as 67,280,421,310,721 without much trouble, although it doesn't seem to handle in Chrome with 170,141,183,460,469,231,731,687,303,715,884,105,727 simply because %2 on that number will be 0. – CTS_AE Nov 21 '16 at 00:52
34

Here is the live demo of this script: http://jsfiddle.net/K2QJp/

First, make a function that will test if a single number is prime or not. If you want to extend the Number object you may, but I decided to just keep the code as simple as possible.

function isPrime(num) {
    if(num < 2) return false;
    for (var i = 2; i < num; i++) {
        if(num%i==0)
            return false;
    }
    return true;
}

This script goes through every number between 2 and 1 less than the number and tests if there is any number in which there is no remainder if you divide the number by the increment. If there is any without a remainder, it is not prime. If the number is less than 2, it is not prime. Otherwise, it is prime.

Then make a for loop to loop through the numbers 0 to 100 and test each number with that function. If it is prime, output the number to the log.

for(var i = 0; i < 100; i++){
    if(isPrime(i)) console.log(i);
}
Evan Kennedy
  • 3,975
  • 1
  • 25
  • 31
  • @argshook wanted to make this comment, but his rep was too low, so I'm adding it on their behalf. "Shouldn't isPrime() loop check if `num % i !== 0` rather than `num % i == 0`?" – Gray Oct 29 '13 at 13:36
  • @Mike - I'm not sure why you're saying that. I verified the output and it logs correctly. For a version without needing to use the console window look [here](http://jsfiddle.net/K2QJp/185/). @Gray / @argshook - That line is for checking if `num` is divisible by `i` or the current number we're checking. If it is divisible by any number less than the current number, we return `false` which means it is not a prime number. – Evan Kennedy Jun 04 '14 at 20:41
  • @EvanKennedy: Sorry but you would have to blame console for that. your snippet in answer // for(var i = 0; i < 100; i++){ if(isPrime(i)) console.log(i); }, doesn't log the correct results. – Mike Jun 06 '14 at 12:13
  • @Mike - It logs the correct results for me. Also, looking at the code, it is a correct (if inefficient) algorithm. – Ted Hopp Mar 09 '15 at 21:15
  • 4
    The code that you propose is not optimized, `i` must be stopped at `sqrt(num)` – Wael Boutglay Dec 17 '15 at 13:50
  • 1
    why we check the number till last, if we check till the middle we decrese the time complexity.... for (var i = 2; i <= num/2; i++) { .... – Srikrushna Jul 27 '18 at 18:15
14

I have slightly modified the Sieve of Sundaram algorithm to cut the unnecessary iterations and it seems to be very fast.

This algorithm is actually two times faster than the most accepted @Ted Hopp's solution under this topic. Solving the 78498 primes between 0 - 1M takes like 20~25 msec in Chrome 55 and < 90 msec in FF 50.1. Also @vitaly-t's get next prime algorithm looks interesting but also results much slower.

This is the core algorithm. One could apply segmentation and threading to get superb results.

"use strict";
function primeSieve(n){
  var a = Array(n = n/2),
      t = (Math.sqrt(4+8*n)-2)/4,
      u = 0,
      r = [];
  for(var i = 1; i <= t; i++){
    u = (n-i)/(1+2*i);
    for(var j = i; j <= u; j++) a[i + j + 2*i*j] = true;
  }
  for(var i = 0; i<= n; i++) !a[i] && r.push(i*2+1);
  return r;
}

var primes = [];
console.time("primes");
primes = primeSieve(1000000);
console.timeEnd("primes");
console.log(primes.length);

The loop limits explained:

Just like the Sieve of Erasthotenes, the Sieve of Sundaram algorithm also crosses out some selected integers from the list. To select which integers to cross out the rule is i + j + 2ij ≤ n where i and j are two indices and n is the number of the total elements. Once we cross out every i + j + 2ij, the remaining numbers are doubled and oddified (2n+1) to reveal a list of prime numbers. The final stage is in fact the auto discounting of the even numbers. It's proof is beautifully explained here.

Sieve of Sundaram is only fast if the loop indices start and end limits are correctly selected such that there shall be no (or minimal) redundant (multiple) elimination of the non-primes. As we need i and j values to calculate the numbers to cross out, i + j + 2ij up to n let's see how we can approach.

i) So we have to find the the max value i and j can take when they are equal. Which is 2i + 2i^2 = n. We can easily solve the positive value for i by using the quadratic formula and that is the line with t = (Math.sqrt(4+8*n)-2)/4,

j) The inner loop index j should start from i and run up to the point it can go with the current i value. No more than that. Since we know that i + j + 2ij = n, this can easily be calculated as u = (n-i)/(1+2*i);

While this will not completely remove the redundant crossings it will "greatly" eliminate the redundancy. For instance for n = 50 (to check for primes up to 100) instead of doing 50 x 50 = 2500, we will do only 30 iterations in total. So clearly, this algorithm shouldn't be considered as an O(n^2) time complexity one.

i  j  v
1  1  4
1  2  7
1  3 10
1  4 13
1  5 16
1  6 19
1  7 22  <<
1  8 25
1  9 28
1 10 31  <<
1 11 34
1 12 37  <<
1 13 40  <<
1 14 43
1 15 46
1 16 49  <<
2  2 12
2  3 17
2  4 22  << dupe #1
2  5 27
2  6 32
2  7 37  << dupe #2
2  8 42
2  9 47
3  3 24
3  4 31  << dupe #3
3  5 38
3  6 45
4  4 40  << dupe #4
4  5 49  << dupe #5

among which there are only 5 duplicates. 22, 31, 37, 40, 49. The redundancy is around 20% for n = 100 however it increases to ~300% for n = 10M. Which means a further optimization of SoS bears the potentital to obtain the results even faster as n grows. So one idea might be segmentation and to keep n small all the time.

So OK.. I have decided to take this quest a little further.

After some careful examination of the repeated crossings I have come to the awareness of the fact that, by the exception of i === 1 case, if either one or both of the i or j index value is among 4,7,10,13,16,19... series, a duplicate crossing is generated. Then allowing the inner loop to turn only when i%3-1 !== 0, a further cut down like 35-40% from the total number of the loops is achieved. So for instance for 1M integers the nested loop's total turn count dropped to like 1M from 1.4M. Wow..! We are talking almost O(n) here.

I have just made a test. In JS, just an empty loop counting up to 1B takes like 4000ms. In the below modified algorithm, finding the primes up to 100M takes the same amount of time.

I have also implemented the segmentation part of this algorithm to push to the workers. So that we will be able to use multiple threads too. But that code will follow a little later.

So let me introduce you the modified Sieve of Sundaram probably at it's best when not segmented. It shall compute the primes between 0-1M in about 15-20ms with Chrome V8 and Edge ChakraCore.

"use strict";
function primeSieve(n){
  var a = Array(n = n/2),
      t = (Math.sqrt(4+8*n)-2)/4,
      u = 0,
      r = [];
  for(var i = 1; i < (n-1)/3; i++) a[1+3*i] = true;
  for(var i = 2; i <= t; i++){
    u = (n-i)/(1+2*i);
    if (i%3-1) for(var j = i; j < u; j++) a[i + j + 2*i*j] = true;
  }
  for(var i = 0; i< n; i++) !a[i] && r.push(i*2+1);
  return r;
}

var primes = [];
console.time("primes");
primes = primeSieve(1000000);
console.timeEnd("primes");
console.log(primes.length);

Well... finally I guess i have implemented a sieve (which is originated from the ingenious Sieve of Sundaram) such that it's the fastest JavaScript sieve that i could have found over the internet, including the "Odds only Sieve of Eratosthenes" or the "Sieve of Atkins". Also this is ready for the web workers, multi-threading.

Think it this way. In this humble AMD PC for a single thread, it takes 3,300 ms for JS just to count up to 10^9 and the following optimized segmented SoS will get me the 50847534 primes up to 10^9 only in 14,000 ms. Which means 4.25 times the operation of just counting. I think it's impressive.

You can test it for yourself;

console.time("tare");
for (var i = 0; i < 1000000000; i++);
console.timeEnd("tare");

And here I introduce you to the segmented Seieve of Sundaram at it's best.

"use strict";
function findPrimes(n){
  
  function primeSieve(g,o,r){
    var t = (Math.sqrt(4+8*(g+o))-2)/4,
        e = 0,
        s = 0;
    
    ar.fill(true);
    if (o) {
      for(var i = Math.ceil((o-1)/3); i < (g+o-1)/3; i++) ar[1+3*i-o] = false;
      for(var i = 2; i < t; i++){
        s = Math.ceil((o-i)/(1+2*i));
        e = (g+o-i)/(1+2*i);
        if (i%3-1) for(var j = s; j < e; j++) ar[i + j + 2*i*j-o] = false;
      }
    } else {
        for(var i = 1; i < (g-1)/3; i++) ar[1+3*i] = false;
        for(var i = 2; i < t; i++){
          e = (g-i)/(1+2*i);
          if (i%3-1) for(var j = i; j < e; j++) ar[i + j + 2*i*j] = false;
        }
      }
    for(var i = 0; i < g; i++) ar[i] && r.push((i+o)*2+1);
    return r;
  }
  
  var cs = n <= 1e6 ? 7500
                    : n <= 1e7 ? 60000
                               : 100000, // chunk size
      cc = ~~(n/cs),                     // chunk count
      xs = n % cs,                       // excess after last chunk
      ar = Array(cs/2),                  // array used as map
  result = [];
  
  for(var i = 0; i < cc; i++) result = primeSieve(cs/2,i*cs/2,result);
  result = xs ? primeSieve(xs/2,cc*cs/2,result) : result;
  result[0] *=2;
  return result;
}


var primes = [];
console.time("primes");
primes = findPrimes(1000000000);
console.timeEnd("primes");
console.log(primes.length);

Here I present a multithreaded and slightly improved version of the above algorithm. It utilizes all available threads on your device and resolves all 50,847,534 primes up to 1e9 (1 Billion) in the ballpark of 1.3 seconds on my trash AMD FX-8370 8 core desktop. While there exists some very sophisticated sublinear sieves, I believe the modified Segmented Sieve of Sundaram could only be stretced this far to being linear in time complexity. Which is not bad.

class Threadable extends Function {
  
  constructor(f){
    super("...as",`return ${f.toString()}.apply(this,as)`);
  }
  
  spawn(...as){
    var code = `self.onmessage = m => self.postMessage(${this.toString()}.apply(null,m.data));`,
        blob = new Blob([code], {type: "text/javascript"}),
        wrkr = new Worker(window.URL.createObjectURL(blob));
    return new Promise((v,x) => ( wrkr.onmessage = m => (v(m.data), wrkr.terminate())
                                , wrkr.onerror   = e => (x(e.message), wrkr.terminate())
                                , wrkr.postMessage(as)
                                ));
  }
}

function pi(n){

  function scan(start,end,tid){
  
    function sieve(g,o){
      var t = (Math.sqrt(4+8*(g+o))-2)/4,
          e = 0,
          s = 0,
          a = new Uint8Array(g),
          c = 0,
          l = o ? (g+o-1)/3
                : (g-1)/3;
      
      if (o) {
        for(var i = Math.ceil((o-1)/3); i < l; i++) a[1+3*i-o] = 0x01;
        for(var i = 2; i < t; i++){
          if (i%3-1) {
            s = Math.ceil((o-i)/(1+2*i));
            e = (g+o-i)/(1+2*i);
            for(var j = s; j < e; j++) a[i + j + 2*i*j-o] = 0x01; 
          }
        }
      } else {
          for(var i = 1; i < l; i++) a[1+3*i] = 0x01;
          for(var i = 2; i < t; i++){
            if (i%3-1){
              e = (g-i)/(1+2*i);
              for(var j = i; j < e; j++) a[i + j + 2*i*j] = 0x01;
            }
          }
        }
      for (var i = 0; i < g; i++) !a[i] && c++;
      return c;
    }
    end   % 2 && end--;
    start % 2 && start--;
    var n  = end - start,
        cs = n < 2e6 ? 1e4   : 
             n < 2e7 ? 2e5   :
                     4.5e5 ,        // Math.floor(3*n/1e3),  // chunk size
        cc = Math.floor(n/cs),      // chunk count
        xs = n % cs,                // excess after last chunk
        pc = 0;
  
    for(var i = 0; i < cc; i++) pc += sieve(cs/2,(start+i*cs)/2);
    xs && (pc += sieve(xs/2,(start+cc*cs)/2));
    return pc;
  }
  var tc = navigator.hardwareConcurrency,
      xs = n % tc,
      cs = (n-xs) / tc,
      st = new Threadable(scan),
      ps = Array.from( {length:tc}
                     , (_,i) => i ? st.spawn(i*cs+xs,(i+1)*cs+xs,i)
                                  : st.spawn(0,cs+xs,i)
                     );
  return Promise.all(ps);
}

var n = 1e9,
    count;

console.time("primes");
pi(n).then(cs => ( count = cs.reduce((p,c) => p+c)
                 , console.timeEnd("primes")
                 , console.log(count)
                 )
          )
     .catch(e => console.log(`Error: ${e}`));

So this is as far as I could take the Sieve of Sundaram.

Redu
  • 25,060
  • 6
  • 56
  • 76
  • How does the sieve of Sundaram compare to the sieve of Eratosthenes with a wheel? They sound very similar. – dfeuer Sep 03 '17 at 02:00
  • @dfeuer Sorry for late response, just saw your comment. I am not sure but there is [this assertive implementation of segmented Erastosthenes on wheel](https://stackoverflow.com/a/27397082/4543207) which checks primes in 1B in 21500 msec (which is really good compared to the others i have seen so far) while this one resolves in like 13500 msec. I also have to modify the code with the Map object instead of using an array for hash. I have some hopes to squeeze a little more juice out from this tangerine before spawning segments on workers. – Redu Oct 01 '17 at 17:35
  • @Redu, I feel that your work using the Sieve of Sundaram, while good, needs my comment: it isn't all that fast compared to a fully optimized "odds-only" bit-packed page segmented Sieve of Eratosthenes as per [my answer here](https://stackoverflow.com/a/27397082/549617) and more specifically the [runnable code here](https://www.w3schools.com/code/tryit.asp?filename=G3142RWABQ66) - your code runs on my Intel x5-Z8350 @ 1.92 GHz in about 39.3 seconds and my code runs in about 6.25/12.25 seconds counting only/enumerating on the same CPU. The SoS is slower due to more and slower operations. – GordonBGood Apr 16 '19 at 08:02
  • @Redu, My answer referenced in your comment has recently been refined to be much faster: As you will see in my added commentary, it is also reasonably easy (although a fair more lines of code) possible to use more wheel factorization to speed this up to count the number of primes to a billion in about 2 seconds on this (slow) CPU by reducing the number of culling operations to a quarter, that only reduces the time to enumerate them to about 5 seconds additional time if that is required. Your code might also benefit from using TypedArray's, bit packing, and only counting the results. – GordonBGood Apr 16 '19 at 08:24
  • @Redu, the reason the SoE is more used than SoE is that even when the number of operations is reduced as you do here, there are still more operations and each operation is more complex. More operations: SoE does all culling of composites based on multiples of prime numbers whereas SoS does it based on all odd numbers, although one could use a "double feed" process as I do in my SoE answer to solve that. Worse is the operational complexity: SoE is a very simple loop, where SoS takes two additions, a multiply and a shift (for times 2). – GordonBGood Apr 17 '19 at 03:05
  • 1
    @Redu (continued)... I suspect that I could optimize SoS to come close to "odds-only" SoE, but there isn't much point as it would be more complex than SoE and even worse if we were to add more wheel factorization as can be done for SoE. – GordonBGood Apr 17 '19 at 03:08
  • @GordonBGood Hi.. thanks for your attention. Agreed with the typed arrays portion though i cant tell how much more performance i can harness by using them. Might give that a try later. I remember reading your answer in the [linked topic](https://stackoverflow.com/a/27397082/4543207) in which you say *This code can sieve to the one billion range is a few 10's of seconds when run on a JavaScript execution engine using Just-In-Time (JIT) compilation such as Google Chrome's V8 engine.* whereas since my code was taking like 14 seconds i felt like not so bad not so good too. **to be continued...** – Redu Apr 17 '19 at 18:46
  • @GordonBGood Also I checked your very efficient recent code which use tons of bitwise operations which would take me to make a lot of look ups (I don't use them daily basis). I would appreciate if you could take some time explain your efficient code like a tutorial. Not only for me but for general JS community since it seems to make a huge difference. Such as the basics of **"The Bit-Packed Page Segmented Sieve of Eratosthenes"** and the algorithm here, under this topic by inserting a live code to the SO sandbox which runs JS. That would be very helpful. – Redu Apr 17 '19 at 18:49
  • @GordonBGood A little smalltalk.. I hate the sieving stuff honestly since it involves no functionality other than just polishing things up and pushing segments to threads in order to gain performance. But then at the end of the day all algoritms are mergining to a similar performance point. There should be a better functional way is what i think. I am thinkering on that a bit however thinkering on an ages long dug topic is hugely discouraging. – Redu Apr 17 '19 at 19:00
  • 1
    @Redu, I don't get "hate the sieving stuff"; in my mind it's all just tuning the algorithm to get the best performance including dividing the work so it can be efficiently multi-processed if that is an option. I dig out these "ages long buried" threads because, while there are many good programmers, many don't have a full understanding of what makes SoE really tick fast, and for the edification of the masses ;) To that end, segmentation has other benefits than just dividing work into slices; it also helps with cache associativity in that each segment should ideally be <= one CPU L1/L2 cache. – GordonBGood Apr 18 '19 at 00:10
  • @Redu, (cont'd) ... Properly using cache is key to speed and justifies the "bit-twiddling" involved in bit packing as in packing more composite number representation into a given size cache. If you need to use LUT's to achieve this, then you may not gain much as a LUT puts a further need on the cache. I don't think you'll find a "better way" than my tuned SoE, which as I say in my updates can be tuned by further wheel factorization to take in the order of a second sieving to a billion on one thread - the former 10's of seconds was an older version. I don't think JS gets better than this... – GordonBGood Apr 18 '19 at 00:29
  • 1
    @Redu, Your suggestion of putting my code(s) in a sandbox with commentary explaining how it works and why it's fast is a good one. This question is maxed out on answers and we are "well past our mandate" on sieving to billions when the question is to hundreds anyway. I've already followed your lead and inserted live code into the other linked answer as per your comment. However, that answer is already getting too big and I don't want to add too much to it. I could add another answer there further expanding on that answer. I don't believe So allows making questions tutorials? Suggestions? – GordonBGood Apr 18 '19 at 00:37
  • @GordonBGood I think it's best if i open a new topic in [Codereview](https://codereview.stackexchange.com/) by pasting this answer of mine, asking for suggestions for further improvement. Then i will let you the link of the question for you to come and show your magic like a tutorial and get accepted. I might possibly do it like tonight – Redu Apr 18 '19 at 13:34
  • @Redu, thanks for preparing the way for my tutorial on CodeReview. Meanwhile, I've found another related question at [Page Segmented SoE in JS](https://stackoverflow.com/questions/39312107/implementing-the-page-segmented-sieve-of-eratosthenes-in-javascript) that seems to need the same treatment and for which I am preparing a tutorial answer. Actually, what I am preaching is an algorithm rather than a program in a particular language and, when the code starts to approach a couple of hundred lines would usually use F# (Fable to transpiler to JS) or Nim. Can CodeReview be language agnostic? – GordonBGood Apr 19 '19 at 00:05
  • @Redu, have a look [at my answer to the above linked question](https://stackoverflow.com/a/55761023/549617) and see if you think it qualifies as a reasonable tutorial. Maybe comment there... – GordonBGood Apr 19 '19 at 11:27
  • 1
    @Redu, in consideration of your proposed look at further optimizations to your SoS code, I don't see much point in that you will be working closer and closer to a SoE algorithm as I cover [in my answer to a ComputerScience algorithm question](https://cs.stackexchange.com/a/107302/26965) other than if you want to take it further for your own better understanding. In fact, your optimization to eliminate certain redundant culls is essentially just a relatively inefficient way of pre-culling to eliminate having to cull the factors of three, for which there are much more efficient ways to do it. – GordonBGood Apr 21 '19 at 07:58
  • 1
    @Redu, (continued) However, Even if you do even a greater level of pre-culling and more efficiently, you will still have more operations than the "odds-only" SoE due to sieving by all odd numbers rather than just by the odd primes, and you still haven't considered "maximum wheel factorization". In other words, with reference to that other "algorithmic" answer, a fully optimized SoS becomes the SoE and you may as well use the Page Segmented SoE and be done with it... – GordonBGood Apr 21 '19 at 08:01
  • 1
    @Redu, Re: my analysis of the SoS as compared to the SoE, I used the same optimizations to implement the PSSoS in exactly the same way as the PSSoE odds-only. One of the things that makes your code slow is that you have too many operations and especially divisions/modulos in your inner culling loop(s) and it turns out that the inner loop can be optimized to only contain simple additions as for SoE. Your elimination of factors of 3 can be done much more efficiently in other ways. However, it's still a O(N (log N)) sieve by not using prime factors; using prime factors would make it a SoE. – GordonBGood Apr 22 '19 at 05:02
  • 1
    @Radu, [here is a runnable version of SoS](https://www.w3schools.com/code/tryit.asp?filename=G3CT2C78AH2S) written with all the same optimizations as the Page Segmented SoE. It is considerably slower than the SoE for the same range of a billion due to sieving for all odd numbers rather than just the primes. It doesn't contain your extra "three" wheel factorization optimization because that wouldn't be comparable to a "odds-only" SoE, for efficiency that should really be implemented as my coming wheel factorized SoE, but then it would lose the simplicity of SoS and still not catch SoE. – GordonBGood Apr 23 '19 at 11:48
  • @GordonBGood Thank you for implementing SoS which looks much better but I will also rephrase it into what i have learned from your tutorial like answer just for practicing. This commenting section is getting over crowded so may be you can reach me from my email which is available in my profile so we may share some thoughts from there. (just copy paste `window.atob(...)` to console and hit enter). – Redu Apr 23 '19 at 11:57
  • Where is 2 in the results? – Caio Tarifa Apr 29 '20 at 20:30
  • @Caio Tarifa You are right at pointing out 2. However you know It's a trivial prime right.? Besides, in the last snipped you will notice that it appears as the head element of the `primes` array. – Redu Apr 29 '20 at 20:50
  • @Redu Yes, but it is easy to solve. https://jsbin.com/pasijecipa/edit?js,console – Caio Tarifa Apr 30 '20 at 04:05
12

Whatever the language, one of the best and most accessible ways of finding primes within a range is using a sieve.

Not going to give you code, but this is a good starting point.

For a small range, such as yours, the most efficient would be pre-computing the numbers.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
8

A number is a prime if it is not divisible by other primes lower than the number in question.

So this builds up a primes array. Tests each new odd candidate n for division against existing found primes lower than n. As an optimization it does not consider even numbers and prepends 2 as a final step.

var primes = [];
for(var n=3;n<=100;n+=2) {
  if(primes.every(function(prime){return n%prime!=0})) {
    primes.push(n);
  }
}
primes.unshift(2);
weston
  • 54,145
  • 21
  • 145
  • 203
4

To find prime numbers between 0 to n. You just have to check if a number x is getting divisible by any number between 0 - (square root of x). If we pass n and to find all prime numbers between 0 and n, logic can be implemented as -

  function findPrimeNums(n)
    { 
       var x= 3,j,i=2,
       primeArr=[2],isPrime;
       for (;x<=n;x+=2){
           j = (int) Math.sqrt (x);
           isPrime = true;
           for (i = 2; i <= j; i++)
           {
                if (x % i == 0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime){
                primeArr.push(x);
            }

        }   

        return primeArr;
    }
Vaibhav
  • 1,479
  • 8
  • 13
4
            var n=100;
            var counter = 0;
            var primeNumbers = "Prime Numbers: ";
            for(var i=2; i<=n; ++i)
            {
                counter=0;
                for(var j=2; j<=n; ++j)
                {
                    if(i>=j && i%j == 0)
                    {
                        ++counter;
                    }

                }
                if(counter == 1)
                    {
                        primeNumbers = primeNumbers + i + "  ";
                    }

            }
            console.log(primeNumbers);
Rahul
  • 130
  • 2
  • ...This answered worked for me and is so much simpler than the other answers I've seen. I'm not sure how j and i get to be different though as they both are rotating at the same time. Could you explain this, thanks? – Joan Aug 04 '20 at 17:25
3

Luchian's answer gives you a link to the standard technique for finding primes.

A less efficient, but simpler approach is to turn your existing code into a nested loop. Observe that you are dividing by 2,3,4,5,6 and so on ... and turn that into a loop.

Given that this is homework, and given that the aim of the homework is to help you learn basic programming, a solution that is simple, correct but somewhat inefficient should be fine.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

Using recursion combined with the square root rule from here, checks whether a number is prime or not:

function isPrime(num){

    // An integer is prime if it is not divisible by any prime less than or equal to its square root
    var squareRoot = parseInt(Math.sqrt(num));
    var primeCountUp = function(divisor){
        if(divisor > squareRoot) {
            // got to a point where the divisor is greater than 
            // the square root, therefore it is prime
            return true;
        }
        else if(num % divisor === 0) {
            // found a result that divides evenly, NOT prime
            return false;
        }
        else {
            // keep counting
            return primeCountUp(++divisor);
        }
    };

    // start @ 2 because everything is divisible by 1
    return primeCountUp(2);

}
Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
3

Here's a fast way to calculate primes in JavaScript, based on the previous prime value.

function nextPrime(value) {
    if (value > 2) {
        var i, q;
        do {
            i = 3;
            value += 2;
            q = Math.floor(Math.sqrt(value));
            while (i <= q && value % i) {
                i += 2;
            }
        } while (i <= q);
        return value;
    }
    return value === 2 ? 3 : 2;
}

Test

var value = 0, result = [];
for (var i = 0; i < 10; i++) {
    value = nextPrime(value);
    result.push(value);
}
console.log("Primes:", result);

Output

Primes: [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]

It is faster than other alternatives published here, because:

  • It aligns the loop limit to an integer, which works way faster;
  • It uses a shorter iteration loop, skipping even numbers.

It can give you the first 100,000 primes in about 130ms, or the first 1m primes in about 4 seconds.

 function nextPrime(value) {
        if (value > 2) {
            var i, q;
            do {
                i = 3;
                value += 2;
                q = Math.floor(Math.sqrt(value));
                while (i <= q && value % i) {
                    i += 2;
                }
            } while (i <= q);
            return value;
        }
        return value === 2 ? 3 : 2;
    }

    var value, result = [];
    for (var i = 0; i < 10; i++) {
        value = nextPrime(value);
        result.push(value);
    }

    display("Primes: " + result.join(', '));

    function display(msg) {
        document.body.insertAdjacentHTML(
            "beforeend",
            "<p>" + msg + "</p>"
        );
    }

UPDATE

A modern, efficient way of doing it, using prime-lib:

import {generatePrimes, stopWhen} from 'prime-lib';

const p = generatePrimes(); //=> infinite prime generator
const i = stopWhen(p, a => a > 100); //=> Iterable<number>

console.log(...i); //=> 2 3 5 7 11 ... 89 97
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
3

You can try this method also, this one is basic but easy to understand:

 var tw = 2, th = 3, fv = 5, se = 7; 

 document.write(tw + "," + th + ","+ fv + "," + se + ",");


for(var n = 0; n <= 100; n++)
{

  if((n % tw !== 0) && (n % th !==0) && (n % fv !==0 ) && (n % se !==0))

  {
      if (n == 1)
      {
          continue;
      }

    document.write(n +",");
  }
}
monika
  • 51
  • 7
3

I recently came up with a one-line solution that accomplishes exactly this for a JS challenge on Scrimba (below).

ES6+

const getPrimes=num=>Array(num-1).fill().map((e,i)=>2+i).filter((e,i,a)=>a.slice(0,i).every(x=>e%x!==0));

< ES6

function getPrimes(num){return ",".repeat(num).slice(0,-1).split(',').map(function(e,i){return i+1}).filter(function(e){return e>1}).filter(function(x){return ",".repeat(x).slice(0,-1).split(',').map(function(f,j){return j}).filter(function(e){return e>1}).every(function(e){return x%e!==0})})};

This is the logic explained:

  1. First, the function builds an array of all numbers leading up to the desired number (in this case, 100) via the .repeat() function using the desired number (100) as the repeater argument and then mapping the array to the indexes+1 to get the range of numbers from 0 to that number (0-100). A bit of string splitting and joining magic going on here. I'm happy to explain this step further if you like.

  2. We exclude 0 and 1 from the array as they should not be tested for prime, lest they give a false positive. Neither are prime. We do this using .filter() for only numbers > 1 (≥ 2).

  3. Now, we filter our new array of all integers between 2 and the desired number (100) for only prime numbers. To filter for prime numbers only, we use some of the same magic from our first step. We use .filter() and .repeat() once again to create a new array from 2 to each value from our new array of numbers. For each value's new array, we check to see if any of the numbers ≥ 2 and < that number are factors of the number. We can do this using the .every() method paired with the modulo operator % to check if that number has any remainders when divided by any of those values between 2 and itself. If each value has remainders (x%e!==0), the condition is met for all values from 2 to that number (but not including that number, i.e.: [2,99]) and we can say that number is prime. The filter functions returns all prime numbers to the uppermost return, thereby returning the list of prime values between 2 and the passed value.

As an example, using one of these functions I've added above, returns the following:

getPrimes(100);
// => [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
  • 1
    Damn! This is exactly the type of approach I was looking for. Thanks for sharing. – ultrageek Jun 20 '20 at 07:26
  • 1
    @ultrageek sure thing! I've further optimized my ES6+ solution to make use of the `fill()` function rather than my somewhat-hacky repeating commas solution. Updated! – Brandon McConnell Jun 23 '20 at 14:58
2
<code>
<script language="javascript">
   var n=prompt("Enter User Value")
     var x=1;
       if(n==0 || n==1) x=0;
          for(i=2;i<n;i++)
           {
          if(n%i==0)
       {
     x=0;
     break;
       }
           }
           if(x==1)
             {
                alert(n +" "+" is prime");
             }
             else
             {
                alert(n +" "+" is not prime");
             }


          </script>

Rinto
  • 21
  • 1
2

Sieve of Eratosthenes. its bit look but its simple and it works!

function count_prime(arg) {

    arg = typeof arg !== 'undefined' ? arg : 20; //default value
    var list = [2]
    var list2 = [0,1]
    var real_prime = []

    counter = 2
    while (counter < arg ) {
        if (counter % 2 !== 0) {
            list.push(counter)
        }
        counter++
    }

    for (i = 0; i < list.length - 1; i++) {
        var a = list[i]
        for (j = 0; j < list.length - 1; j++) {
            if (list[j] % a === 0 && list[j] !== a) {
                list[j] = false;       // assign false to non-prime numbers
            }
        }
        if (list[i] !== false) { 
            real_prime.push(list[i]);  // save all prime numbers in new array
        }
    }
 }
window.onload=count_prime(100);
Abdullah Aden
  • 882
  • 9
  • 13
  • as written, this is not the sieve of Eratosthenes. there are several answers here with the correct implementation of the sieve. you can study them, and amend your answer. When you do, please do not use tabs, they mess up formatting here, use only spaces please. And your closing parenthesis is missing. – Will Ness Nov 13 '14 at 20:22
  • thank you for feedback @ness. I did it reading explanation of Sieve of Eratosthenes on wikipedia. there are better fancy solutions but i dnt want to copy. thanks again – Abdullah Aden Nov 15 '14 at 11:18
  • fancy or not, as long as you're checking the modulo operation for each number, that's just not the sieve of Eratosthenes. You can turn it into one, if you change your inner `for` loop: change the starting point and the increment so that the test is guaranteed to be `true` always, by construction - so you can just *omit* the test. And that's what the proper s. of E. is all about. – Will Ness Nov 15 '14 at 18:00
2

Here's my stab at it.

Change the initial i=0 from 0 to whatever you want, and the the second i<100 from 100 to whatever to get primes in a different range.

for(var i=0; i<100000; i++){
    var devisableCount = 2;

    for(var x=0; x<=i/2; x++){
        if (devisableCount > 3) {
            break;
        }
        if(i !== 1 && i !== 0 && i !== x){
            if(i%x === 0){
               devisableCount++;
             }
        }
    }

    if(devisableCount === 3){
        console.log(i);
    }
}

I tried it with 10000000 - it takes some time but appears to be accurate.

shanehoban
  • 870
  • 1
  • 9
  • 30
2

And this famous code from a famous JS Ninja

var isPrime = n => Array(Math.ceil(Math.sqrt(n)+1)).fill().map((e,i)=>i).slice(2).every(m => n%m);

console.log(Array(100).fill().map((e,i)=>i+1).slice(1).filter(isPrime));
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
2

A list built using the new features of ES6, especially with generator. Go to https://codepen.io/arius/pen/wqmzGp made in Catalan language for classes with my students. I hope you find it useful.

function* Primer(max) { 
  const infinite = !max && max !== 0;
  const re = /^.?$|^(..+?)\1+$/; 
  let current = 1;
 
  while (infinite || max-- ) {
      if(!re.test('1'.repeat(current)) == true) yield current;
      current++
  };
};


let [...list] = Primer(100); 
console.log(list);
arius
  • 79
  • 1
  • 1
2

Here's the very simple way to calculate primes between a given range(1 to limit).

Simple Solution:

    public static void getAllPrimeNumbers(int limit) {

        System.out.println("Printing prime number from 1 to " + limit);

        for(int number=2; number<=limit; number++){
            //***print all prime numbers upto limit***
            if(isPrime(number)){
                System.out.println(number);
            }
        }
    }


    public static boolean isPrime(int num) {
        if (num == 0 || num == 1) {
            return false;
        }
        if (num == 2) { 
            return true;
        }

        for (int i = 2; i <= num / 2; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
ManishS
  • 627
  • 2
  • 11
  • 21
  • 2
    there already is a similar yet [much better answer](https://stackoverflow.com/a/25823456/849891) here. [another](https://stackoverflow.com/a/27018835/849891) is essentially the same as this one. do we really need another replica of a bad answer? (with all due respect; no hard feelings) – Will Ness Jan 10 '18 at 19:57
2

Here is an efficient, short solution using JS generators. JSfiddle

// Consecutive numbers starting from n
function* nats (n) {
    while (true) yield n++
}

// Recursively sift primes, starting with the stream of numbers 2 and above
function* primes () {
    yield* sieve(primes(), nats(2))
}

// Take a stream of primes and the stream of already-sifted numbers, and
//   recursively yield from streams of numbers each time sifted by a new prime
function* sieve (ps, ns) {

    // The first new already-sifted number must also be prime
    // (In the first call, this loads a 2 into the prime stream to begin
    //   sifting)
    yield ns.next().value;
    let n;

    // Get p, the new prime which this sieve focuses on
    const p = ps.next().value;

    // Yield already-sifted numbers up to p^2
    while ((n = ns.next().value) < p * p) yield n;

    // Yield from a new sieve that also removes p-divisible numbers
    yield* sieve(ps, (function* () {
        while (n = ns.next().value) if (n % p) yield n
    })())

}

// Longest prefix of stream where some predicate holds
function* take (vs, pf) {
    let v;
    while (!(v = vs.next()).done && pf(v.value)) yield v.value
}

document.querySelectorAll('dd')[0].textContent =

// Primes smaller than 100
    [...take(primes(), x => x < 100)].join(', ')
<dl>
<dt>Primes under 100</dt>
<dd></dd>
</dl>
den-chan
  • 95
  • 9
  • Nice! nice to see the postponed sieving scheme taking hold. have you seen it somewhere or come up with it yourself? :) – Will Ness Jul 02 '23 at 19:14
2

A version without any loop. Use this against any array you have. ie.,

[1,2,3...100].filter(x=>isPrime(x));
const isPrime = n => {
if(n===1){
return false;
}
if([2,3,5,7].includes(n)){
return true;
}
return n%2!=0 && n%3!=0 && n%5!=0 && n%7!=0;
}
ABD
  • 49
  • 8
  • Please have a read of the [formatting help page](https://stackoverflow.com/editing-help) to improve the formatting in your answer, and also check out [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) to improve your answer. – costaparas Feb 16 '21 at 05:37
1
  • Why try deleting by 4 (and 6,8,10,12) if we've already tried deleting by 2 ?
    Why try deleting by 9 if we've already tried deleting by 3 ?
    Why try deleting by 11 if 11 * 11 = 121 which is greater than 100 ?
    Why try deleting any odd number by 2 at all?
    Why try deleting any even number above 2 by anything at all?

Eliminate the dead tests and you'll get yourself a good code, testing for primes below 100.

And your code is very far from being the worst code ever. Many many others would try dividing 100 by 99. But the absolute champion would generate all products of 2..96 with 2..96 to test whether 97 is among them. That one really is astonishingly inefficient.

Sieve of Eratosthenes of course is much better, and you can have one -- under 100 -- with no arrays of booleans (and no divisions too!):

console.log(2)
var m3 = 9, m5 = 25, m7 = 49, i = 3
for( ; i < 100; i += 2 )
{
    if( i != m3 && i != m5 && i != m7) console.log(i)
    else
    {
        if( i == m3 ) m3 += 6
        if( i == m5 ) m5 += 10
        if( i == m7 ) m7 += 14
    }
} "DONE"

This is the sieve of Eratosthenes, were we skip over the composites - and that's what this code is doing. The timing of generation of composites and of skipping over them (by checking for equality) is mixed into one timeline. The usual sieve first generates composites and marks them in an array, then sweeps the array. Here the two stages are mashed into one, to avoid having to use any array at all (this only works because we know the top limit's square root - 10 - in advance and use only primes below it, viz. 3,5,7 - with 2's multiples, i.e. evens, implicitly skipped over in advance).

In other words this is an incremental sieve of Eratosthenes and m3, m5, m7 form an implicit priority queue of the multiples of primes 3, 5, and 7.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • Why do we need to check till 100? why not till square root of 100 alone? – Om Shankar Oct 16 '14 at 13:32
  • we generate up to 100, aren't we? it's the sieve of Eratosthenes, were we skip over the composites - and that's what this code is doing. The timing of generation of composites and of skipping over them (by checking for *equality*) is mixed into one timeline. The usual sieve first generates composites and marks them in an array, then sweeps the array. Here the two stages are mashed into one, to avoid having to use any array at all (this only works because we know the top limit's square root - 10 - in advance and use only primes below it, viz. 3,5,7 - with 2 implicitly skipped in advance). – Will Ness Oct 16 '14 at 14:36
  • @OmShankar IOW, this is an *incremental* sieve of Eratosthenes and `m3`, `m5`, `m7` form an implicit priority queue of multiples of the primes 3, 5, and 7. – Will Ness Oct 16 '14 at 14:42
  • How would we extend it to 1000, or 10,000? Do we generate more `m`s, like `m11, m13` etc. – Om Shankar Oct 16 '14 at 15:54
  • @OmShankar yes, but -- to 10k you need primes below 100. there are 25 of them. using 25 variables explicitly isn't good. Either have a bona fide priority queue, or just use the regular sieve of E. with arrays then. Normally you'd go by segments - smaller arrays that fit in the memory cache, - and sieve them one after another. 10K is really a very small number and can be done in one segment. – Will Ness Oct 16 '14 at 16:08
1

Using Sieve of Eratosthenes, source on Rosettacode

fastest solution: https://repl.it/@caub/getPrimes-bench

function getPrimes(limit) {
    if (limit < 2) return [];
    var sqrtlmt = limit**.5 - 2;
    var nums = Array.from({length: limit-1}, (_,i)=>i+2);
    for (var i = 0; i <= sqrtlmt; i++) {
        var p = nums[i]
        if (p) {
            for (var j = p * p - 2; j < nums.length; j += p)
                nums[j] = 0;
        }
    }
    return nums.filter(x => x); // return non 0 values
}
document.body.innerHTML = `<pre style="white-space:pre-wrap">${getPrimes(100).join(', ')}</pre>`;

// for fun, this fantasist regexp way (very inefficient):
// Array.from({length:101}, (_,i)=>i).filter(n => n>1&&!/^(oo+)\1+$/.test('o'.repeat(n))
caub
  • 2,709
  • 2
  • 28
  • 31
1

Here are the Brute-force iterative method and Sieve of Eratosthenes method to find prime numbers upto n. The performance of the second method is better than first in terms of time complexity

Brute-force iterative

function findPrime(n) {
  var res = [2],
      isNotPrime;

  for (var i = 3; i < n; i++) {
    isNotPrime = res.some(checkDivisorExist);
    if ( !isNotPrime ) {
      res.push(i);
    }
  }

  function checkDivisorExist (j) {
    return i % j === 0;
  }

  return res;
}

Sieve of Eratosthenes method

function seiveOfErasthones (n) {
  var listOfNum =range(n),
      i = 2;

  // CHeck only until the square of the prime is less than number
  while (i*i < n && i < n) {
    listOfNum = filterMultiples(listOfNum, i);
    i++;
  }

  return listOfNum;


  function range (num) {
    var res = [];
    for (var i = 2; i <= num; i++) {
      res.push(i);
    }
    return res;
  }

  function filterMultiples (list, x) {
    return list.filter(function (item) {
      // Include numbers smaller than x as they are already prime
      return (item <= x) || (item > x && item % x !== 0);
    });
  }
}
Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
1

You can use this for any size of array of prime numbers. Hope this helps

 function prime() {
   var num = 2;

   var body = document.getElementById("solution");

   var len = arguments.length;
   var flag = true;

   for (j = 0; j < len; j++) {

     for (i = num; i < arguments[j]; i++) {

       if (arguments[j] % i == 0) {
         body.innerHTML += arguments[j] + " False <br />";
         flag = false;
         break;

       } else {
         flag = true;

       }

     }
     if (flag) {
       body.innerHTML += arguments[j] + " True <br />";

     }

   }

 }

 var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

 prime.apply(null, data);
<div id="solution">

</div>
Aslam
  • 9,204
  • 4
  • 35
  • 51
1
public static void main(String[] args) {
    int m = 100;
    int a[] =new int[m];
    for (int i=2; i<m; i++)
        for (int j=0; j<m; j+=i)
            a[j]++;
    for (int i=0; i<m; i++)
        if (a[i]==1) System.out.println(i);
}
  • We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed. – gdlmx Sep 11 '17 at 16:37
1

I was searching how to find out prime number and went through above code which are too long. I found out a new easy solution for prime number and add them using filter. Kindly suggest me if there is any mistake in my code as I am a beginner.

function sumPrimes(num) {

let newNum = [];

for(let i = 2; i <= num; i++) {
newNum.push(i)
}
for(let i in newNum) {

newNum = newNum.filter(item => item == newNum[i] || item % newNum[i] !== 0)
}

return newNum.reduce((a,b) => a+b)
}

sumPrimes(10);
0

First, change your inner code for another loop (for and while) so you can repeat the same code for different values.

More specific for your problem, if you want to know if a given n is prime, you need to divide it for all values between 2 and sqrt(n). If any of the modules is 0, it is not prime.

If you want to find all primes, you can speed it and check n only by dividing by the previously found primes. Another way of speeding the process is the fact that, apart from 2 and 3, all the primes are 6*k plus or less 1.

SJuan76
  • 24,532
  • 6
  • 47
  • 87
0

It would behoove you, if you're going to use any of the gazillion algorithms that you're going to be presented with in this thread, to learn to memoize some of them.

See Interview question : What is the fastest way to generate prime number recursively?

Community
  • 1
  • 1
alvonellos
  • 1,009
  • 1
  • 9
  • 27
0

Use following function to find out prime numbers :

function primeNumbers() {
    var p
    var n = document.primeForm.primeText.value
    var d
    var x
    var prime
    var displayAll = 2 + " "
    for (p = 3; p <= n; p = p + 2) {
        x = Math.sqrt(p)
        prime = 1
        for (d = 3; prime && (d <= x); d = d + 2)
        if ((p % d) == 0) prime = 0
        else prime = 1
        if (prime == 1) {
            displayAll = displayAll + p + " "
        }
    }
    document.primeForm.primeArea.value = displayAll
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
user1598202
  • 250
  • 1
  • 2
0

check the number is prime or not with JS function

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;    
        }
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
0

Here is a way to test if number is prime number.

function isPrime(numb){
  if (numb % 2 == 0) return false;
  for (var i=3; i<= Math.sqrt(numb); i = i + 2) {
    if (numb % i == 0) {
     return false;
    }
  }
  return true;
}
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Bray
  • 361
  • 1
  • 10
  • Can u explain why `i = i + 2` and not `i++`? – Om Shankar Oct 16 '14 at 13:04
  • @OmShankar starting from 3, incrementing by 2 will enumerate all odd numbers - no need to test any even above 2, as by definition they are all non-prime. – Will Ness Oct 16 '14 at 15:54
  • Ya got it. Missed that simple thing. We can also check `num % 3 == 0` to avoid entering the for loop for multiples of 3. And this can **may be** extended to eventually reach the Sieve of Eratosthenes, as in ur version of the answer. – Om Shankar Oct 16 '14 at 15:59
  • @OmShankar no, if you test for `n % 3`, then you test it. the point is to *not* have to test it, if you avoid it *by construction*. For mults of 3, you could use `for(i=5, k=4; i*i <= num; i+= (k=6-k)) { ...use i... }` or `for(i=5, j=7; j*j<= num; i+=6, j+=6) { ...use i... ; ...use j... }`. – Will Ness Oct 16 '14 at 16:16
0

I modified Rinto's answer just for those who don't want to use the prompt method and just want to see the program print prime numbers . its working

for (n = 0; n < 100; n++) {
    var x = 1;
    if (n == 0 || n == 1) x = 0;
    for (i = 2; i < n; i++) {
        if (n % i == 0) {
            x = 0;
            break;
        }
    }
    if (x == 1) {
        // if prime print the numbers 
        document.write(n);
    } else {
        // if not prime print the number do nothing 
    }
}
Om Shankar
  • 7,989
  • 4
  • 34
  • 54
Humphrey
  • 2,659
  • 3
  • 28
  • 38
0

How about something like this.

next_prime:
for (var i = 2; i < 100; i++){
    for (var e = 2; e < i; e++){
        if (i % e === 0) continue next_prime;
    }
    console.log(i + '<br>');
}
barrakuda
  • 11
  • 3
0

This is my solution

//find all prime numbers
function showMePrimeNumbers(start, end){
    var primes = [];
    for(var number = start; number < end; number++){
        var primeNumberDividers = []; //there should only be 2: 1 & number
        for(var divider = 1; divider <= number; divider++){
            if(number % divider === 0){
                primeNumberDividers.push(divider);
            }      
        }
        if(primeNumberDividers.length === 2){
            primes.push(number);
        }
    }
    return primes;
}

console.log(showMePrimeNumbers(1, 100));           
codeepic
  • 3,723
  • 7
  • 36
  • 57
0

I have created a JSFiddle showing how it should work in a readable way,

idea is to have two functions isPrime and getPrimeNumbers to separate functionality, as well as using Math.pow and initial value of 2, as it should be always there, see the jsfiddle attached jsFiddle

window.onload = function() {
  (function() {
    var cont = document.getElementById('MainContainer');
    var curEl = document.createElement('span');
    var primeNumbers = [2];

    function fillContent() {
        var primeNumbersContent = document.createTextNode(JSON.stringify(primeNumbers));
        curEl.appendChild(primeNumbersContent);
        cont.appendChild(curEl);
    }

    function isPrime(n) {
        var divisor = 2;
        while (n > divisor) {
            if (Math.pow(divisor, 2) > n) {
                return true;
            }
            if (n % divisor == 0 || Math.sqrt(divisor) > n) {
                return false;
            } else {
                divisor++;
            }
        }
        return true;
    }

    function getPrimeNumbers(range) {
        for (var i = 3; i <= range; i+=2) {
            if (isPrime(i)) {
                primeNumbers.push(i);
            }
        }
        fillContent(primeNumbers);
    }
    getPrimeNumbers(11);
  })();
};
0

Here is my solution using Sieve of Eratosthenes method:

function gimmePrimes(num) {
  numArray = [];
  // first generate array of numbers [2,3,...num]
  for (i = 2; i <= num; ++i) {
    numArray.push(i);
  }

  for (i = 0; i < numArray.length; ++i) {
    //this for loop helps to go through each element of array

    for (j = numArray[i]; j < numArray[numArray.length - 1]; ++j) {
      //get's the value of i'th element
      for (k = 2; j * k <= numArray[numArray.length - 1]; ++k) {
        //find the index of multiples of ith element in the array
        index = numArray.indexOf(j * k);
        if (index > -1) { //remove the multiples
          numArray.splice(index, 1);
        }
      }

    }
  }
  return numArray; //return result
}
gimmePrimes(100);
Nigel
  • 387
  • 4
  • 13
0
function isPrime(num) {
  for(var i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num ;
}
function primes(n){
  var array_of_primes=[];
for(var i = 2; i < n; i++){
    if(isPrime(i)) array_of_primes.push(i)>1;
     }
   return array_of_primes;
}
document.write(primes(10000));
  • 2
    While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – SherylHohman May 31 '20 at 18:11
-1
<html>
<head>
<script type="text/javascript">
function primeNumber() {
 x=document.getElementById('txt_field').value;
  for (i=1; i<=parseInt(x); i++) {
  var flag=0,flag1=0; 
    for (j=2; j<i; j++) {
      if(i%j==0){
       flag=1;
      if(i==x)
       flag1=1;
      }
    }
   if(flag==0)
    document.write(i+'<br>');
  }
   if(flag1==0) 
    document.write('Its a prime number.');
   else 
    document.write('Its not a prime number.');
}
</script>
</head>

<body>
 <input id="txt_field" type="text" name="field" />
 <input type="button" name="submit" value="Submit" onclick="primeNumber();" />
</body>
</html>
Snooze
  • 35
  • 1
  • 3
-1

Did anyone try this? It's simple and efficient ...

function Prime(num) {
  if (num <= 2)return false;
  for(var i = 2; i < num; i++){
    if (num % i == 0) return false;
  }
  return true;
}

function PrimeWithin(userinput){
  for(var i = 2; i < userinput; i++){
    if(Prime(i)){
        console.log(i);
    }
  }
}

PrimeWithin(500);
Magicprog.fr
  • 4,072
  • 4
  • 26
  • 35
DanJC
  • 1