13

I am writing a JavaScript to generate prime numbers from 2 to 100. However It doesn't work and can't figure it out.

will you help me please?

var array = new Array(100);

for (var i=2 ; i<=array.length-1; i++) {
    if((i%2===0) || (i%3===0))
        continue;
    document.writeln(i+",");
}

I modified my answer, but now it doesn't print 2 & 3; how can I include 2 & 3... result is :

5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97

e666
  • 1,308
  • 12
  • 20
SamR
  • 527
  • 3
  • 10
  • 23
  • 1
    Please provide a better description than "it doesn't work". What do you expect the code to do and what does it actually do? – Felix Kling Feb 23 '14 at 08:38
  • 3
    1) Your code only checks to see if the number is divisible by 2 or 3, 2) it returns false after the first number that's not a 'prime' is found. 3) you never add new primes to `array` 4) even if you did add primes to `array`, you increment `prime` by `array[i]` which will skip many primes. – p.s.w.g Feb 23 '14 at 08:39
  • why "i++" instead of "i+=2", are even numbers ever prime? you also only need examine just past half of the number your're checking for a prime... – dandavis Feb 23 '14 at 08:45
  • @p.s.w.g thank you, I'm going to try it and will let you know :) – SamR Feb 23 '14 at 08:48
  • @dandavis 2 is the only even prime. Usually that's hard coded as a prime and code assumes all others are odd. – p.s.w.g Feb 23 '14 at 08:48
  • as written, it starts at 2, then goes to 3, then to 4. i'm sayin one could start at 3 and then go to 5 then 7... why do extra work that you don't have to? – dandavis Feb 23 '14 at 08:49
  • See my post, it is posting every prime number from 2 to `N`, which you specify in `display` function – nanobash Feb 24 '14 at 18:54
  • Updated answer, though first post is correct as well... – nanobash Feb 24 '14 at 19:24

21 Answers21

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

function display(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr); // use arr result on your own
}

display(100);

NOTE: Specify n parameter in display function and get the primes from 2 to n ...

Check out JSFiddle

Updateing: Note that the above script is correct and I'm leaving it, though adding the same function with one functionality in addition:

function prime(n,flag) {
    ( typeof flag === "undefined" || flag === false ) ? flag = false : flag = true;

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

    if ( flag ) {
        var arr = [2];
        for ( var i = 3; i <= n; i+=2 ) {
            if ( isPrime(i) ) {
                arr.push(i);
            }
        }
        return arr;
    } else {
        return isPrime(n);
    }
}

Explanation: prime function expect two parameters, first one is required and the second is optional. If only first parameter is specified function will return true or false based on number belongs or not to primes. If second parameter is specified as true (or any other type except undefined and false) function will return array of primes from 2 to n. For example:

console.log(prime(2)); // returns true ( 2 is prime )
console.log(prime(8)); // returns false ( 8 isn't prime )

console.log(prime(100,true)); // returns [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]
nanobash
  • 5,293
  • 7
  • 34
  • 56
  • 3
    Your solution is rather inefficient. The display loop better started from 3 and incremented by 2 and isPrime only needs to divide by prime numbers. – Christoph Feb 23 '14 at 12:32
  • @Christoph I've tested elapsed time between discussed solution algorithms and difference occurs sensible about 100 milliseconds when `N` is `100000` – nanobash Feb 23 '14 at 16:48
  • 2
    You only need to check up to the square root of `num`. – None May 24 '16 at 16:30
  • I'm trying to understand how the function `isPrime(num)` works. What I can understand is that the `function display(n)` produce this array [2,3,5,7,9] and so on with odd numbers. Next, this array is filtered through `function isPrime(num)`. Starting with `var i = 2; i < num; i++` and using this equation `num % i === 0`, it should go like this, 3(num) % 2(i) has remainder, 5(num) % 3(i) has remainder, 7(num) % 4(i) has remainder, but the next one, 9(num) % 5(i) also have remainder but 9 isn't a prime number. What is supposed to happen? – Kristina Bressler Jul 28 '17 at 05:22
  • @KristinaBressler if you specify n number as an argument without flag, flag considered to be a false and function returns whether specified integer is prime number or not. On the other hand if flag set to true, function returns prime numbers up to specified n integer. Inside isPrime function determines whether number is prime or not by checking the reminder, whether number can be divided to any number up to specified n number, and returns boolean based on it. and Yes 9 is not a prime nuber. function returns false if you try. – nanobash Jul 28 '17 at 08:02
  • Umm...I'm asking about the first solution, not the second updated solution that you posted. I wanted to know if the output is correct for this condition `num % i === 0`: 3(num) % 2(i), 5(num) % 3(i), 7(num) % 4(i), 9(num) % 5(i), 11(num) % 6(i), and so on... – Kristina Bressler Jul 28 '17 at 20:19
  • @KristinaBressler Yes it is correct if we don't consider passing in `isPrime` function 0, 1 and 3 values. In order to work for those values add `if clause` from updated version. – nanobash Jul 31 '17 at 08:08
8
var enterNumber = prompt("Enter number: ");

for(var i=2; i<=enterNumber ;i++){

        var isPrime = true;

        for(var j=2; j<i; j++){
            if(i%j === 0 && i !== j){
                isPrime = false;
            }
        }
        if(isPrime === true){
            console.log(i);
        }
    }
ABDUL JAMAL
  • 392
  • 5
  • 10
Kamil Bagi
  • 81
  • 1
  • 2
7

Your original code has numerous flaws. To implement the Sieve of Eratosthenes, you need to add each prime you find to an array, and then test the next candidate prime against every prime you've found so far. If the candidate is not divisible by any of the primes in the array, then it's prime, and you can add it to your array of primes.

Here's a working version (Demonstration):

function start() {    
    var array = [2, 3];
    for (var i = 5; i <= 100; i += 2) {
        if (array.every(function(p) { return i % p; })) {
            array.push(i);
        }
    }
    var result = array.join(",");
    document.getElementById("output").innerHTML = result;
}
start();

Note that this depends on Array.prototype.every which was introduced in ECMAScript 5.

p.s.w.g
  • 141,205
  • 29
  • 278
  • 318
  • Strictly spoken this is not the SoE. You test each number multiple times, which is against the purpose of SoE. Look at the second solution of my answer, which is a SoE. – Christoph Feb 23 '14 at 09:28
7

A version using javascript generators:

function* take(length, iterable) {
  for (let x of iterable) {
    if (length <= 0) return;
    length--;
    yield x;
  }
}

function* primes() {
  let n = 2;

  while (true) {
    if (isPrime(n)) yield n;
    n++;
  }

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

console.log([...take(4, primes())]); //[ 2, 3, 5, 7 ]
Ruslan López
  • 4,289
  • 1
  • 25
  • 36
Alexandru Olaru
  • 6,380
  • 4
  • 25
  • 51
3

You have a lot of ways to achieve this.

You were basically on the right way, however, you have to check every number if it's divisible by every prime you determined so far:

var primes = [2],isPrime;

for (var i=3;i<100;i+=2){
    isPrime = true;
    // test the number you are examaning against
    // all the primes you found so far
    for (var j = 0;j<primes.length;j++){
        if (i%primes[j]==0){
            isPrime=false;
            break;
        }
    }
    if(isPrime){primes.push(i)}
}
console.log(primes);

See the result here

Or you can use the Sieve of Eratosthenes which sorts out all numbers to avoid duplicated tests.

A true implementation of the SoE:

// initialize the array first
var numbers = [], primes = [], maxNumber = 100;

for(var i = 2;i<=maxNumber;i++){
 numbers.push(i);   
}

while(numbers.length){
    primes.push(numbers.shift());
    numbers = numbers.filter(
        function(i){return i%primes[primes.length-1]!=0}
    );
}

console.log(primes);

Demo

Christoph
  • 48,137
  • 19
  • 97
  • 125
2

this might be an efficient way :

function calcPrimes(max){
    var primes = [];
    for(var i=2; i<=max; i++){
        var isPrime = true; 
        for(var j=0; j<primes.length; j++){
            var p = primes[j];
            if( i % p === 0){
                //it is divisible by another prime, so it's not prime
                isPrime=false;
                break;
            }
            //you don't need to check primes bigger than sqrt(i)
            if(p*p > i)
                break;
         }
        if(isPrime)
            primes.push(i);
    }
    console.log(JSON.stringify(primes))
    console.log(primes.length)
}
calcPrimes(100);
SinaX
  • 7
  • 3
1

Here's a working example of how to generate an unlimited number of primes, using a variation of the Sieve of Eratosththenes. It is a true SoE, and does not perform trial division to determine if a number is prime. It may look a little bit strange, but this is because it is designed to work without any upper bound.

<input type=button value="Start" onClick="do_cancel(); do_once()">
<input type=button value="Stop" onClick="do_cancel()">
<table id="mytable"></table>

<script>
'use strict';
(function () {
    var ptable = document.getElementById("mytable");
    var prow = [2, 3];
    function insertPrimeIntoTable(prime) {
        prow.push(prime);
        if( prow.length < 10 ) return false;
        var tr = document.createElement('tr');
        for( var i = 0; i < prow.length; ++i ) {
            var cell = document.createElement('td');
            cell.appendChild( document.createTextNode( prow[i] ) );
            tr.appendChild( cell );
        }
        ptable.appendChild( tr );
        prow = [];
        return true;
    };

    var factors = [];
    function insertPrimeIntoSieve( factor ) {
        var where = factor;
        while( factors[where] )
            where += factor;
        /* while( factors.length < where ) factors.push(0); */
        factors[ where ] = factor;
    }

    var primes = [];
    var a_prime = 3, a_squared_prime = 9, maybe_prime = 3;
    var canceller;
    function do_once() {
        var factor = factors[0];
        maybe_prime += 2;
        if( factor ) {
            //if( 0 != (maybe_prime % factor) )
            //  throw "Unexpected remainder.";
            insertPrimeIntoSieve( factor );
        } else if( maybe_prime < a_squared_prime ) {
            insertPrimeIntoTable( maybe_prime );
            primes.push( maybe_prime );
        } else if( maybe_prime == a_squared_prime ) {
            insertPrimeIntoSieve( a_prime );
            a_prime = primes.shift();
            a_squared_prime = a_prime * a_prime;
        } else {
            throw "Critical math failure:  Programmer or compiler is innumerate.";
        }
        factors.shift();
        canceller = window.setTimeout( do_once, 5 );
    };
    function do_cancel() {
        if( canceller ) window.clearTimeout( canceller );
        canceller = null;
    }
    window.do_once = do_once;
    window.do_cancel = do_cancel;
})();
</script>
BenGoldberg
  • 385
  • 2
  • 6
1

Here's a naive functional answer:

const prime = to => [...Array(to-1).keys()].map(i=>i+2).filter(n =>
  [...Array(n-2).keys()].map(i=>i+2).reduce((acc,x)=> acc && n % x !== 0, true)
)

This will return an array with all primes.

Hugo Elhaj-Lahsen
  • 4,009
  • 3
  • 11
  • 30
1

We can find prime number upto n with only one loop, also I am increasing loop by +2:

function primeNumber(n) {
    let arr = [2];
    for (let i = 3; i <= n; i += 2)
        if (!((i % 3 == 0 && i > 3) || (i % 5 == 0 && i > 5) || (i % 7 == 0 && i > 7) || (i % 9 == 0 && i > 9))) {
            arr.push(i);
        }
    return arr;
}
primeNumber(100);
// output: [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]

Time complexity would be o(n/2);

ashish siddhu
  • 181
  • 1
  • 5
0
function isPrime(num) {
    if (num % 2 == 0) {
        return false;
    }

    let n = Math.sqrt(num);

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

    return true;
}

function print(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr);
}

print(100);
user8640104
  • 728
  • 6
  • 7
0
Please try this,
var a = [...Array(100).keys()];
var primeNumbers = a.map(v => { 
    if (v % 2 === 0 || v % 3 === 0) { 
      if (v === 2 || v === 3) {
       return v;
      } else {
       return;
      } 
    } else {
      return v;
    }
});

primeNumbers.filter(val => val);

you will get 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97
0

I know this question is asked 2014, but just in case if OP or anyone wondering about how to generate small prime numbers using Javascript, I have shared the small JS code in https://github.com/HMaxF/generate-small-prime-number.

In my macbook pro, I can generate all prime numbers from 2 up to 100 millions in around 25 seconds, but your machine result will vary.

hmaxf2
  • 616
  • 5
  • 10
0

I agree with p.s.w.g. Your original code has numerous flaws.

var prime = [2,3,5,7];

for(var x = 0; x < 100; x++){
    var isPrime = prime.map(n => x%n > 0).filter(t => !t).length <= 0;
    if(isPrime || prime.includes(x)){
        console.log(x);
   }
}
Vahe Gharibyan
  • 4,207
  • 2
  • 29
  • 39
0

function printPrimes(num) {
 let sum = []
  for(let i = 2; i<=num; i++) {
  if(check(i)) {
   sum.push(i)
  }
 }
 return sum
}
function check(num) {     // function to check number is prime or not
 if(num <= 1 || typeof num !== 'number') {
  return false
 }else if(num ===2) {
  return true
 }else if (num%2 === 0) {
  return false
 }
 for(let i=3; i*i <= num;i +=2) {
  if(num%i === 0) {
   return false
  }
 }
   return true
} 
console.log(printPrimes(100))
0

Simply Use this Java Script for Prime Numbers from 2 to your desired number:

function primeFactorsTo(num)
{
    var store  = [], i, j, primes = [];
    for (i = 2; i <= num; ++i) 
    {
        if (!store [i]) 
          {
            primes.push(i);
            for (j = i << 1; j <= num; j += i) 
            {
                store[j] = true;
            }
        }
    }
    return primes;
}

console.log(primeFactorsTo(200));
Vinod Bokde
  • 308
  • 2
  • 14
0
I’ve Made the easiest Algorithm to solve this Problem

Step 1 –  Create a function to check a number is prime or not  (PrimeFilter) .

Step 2 – Create another function to print prime numbers smaller than given  number ,
               inside it declare an empty array .
Step 3 – Loop from 2 ( first prime number ) to the given number , and pass every loop value
              to the function PrimeFilter ( It will check every loop value if its prime or not ) .
Step 4 – If its a prime add it to the empty array .   Thats it :)


    function PrimeFilter(num){
         if(num===0){
           return false;
        }
        else if(num===1){
            return false;
        }

        else if(num===2){
            return true;
        }

        else {

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

     function UptoPrime(number){
        var List =[];
         for(var i=2; i<=number; i++){
            if(PrimeFilter(i)){ 
                List.push(i);
            }
         }
         console.log(List.join(' '));
    }
0

with refernece to this answer this checks for prime numbers and prints the desired no of prime between given range

const isPrime = num => {
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}

primes = [] ;

for(let i = 2; i < max ; i ++) {
if(isPrime(i)) {
   primes.push(i)
 }
}

console.log(primes);
0

a while ago i came up with a typescript class with a generator fn, thought it might be of use.

export default class PrimeNumbers {
_number: number
_primes: Array<Buffer> = []

constructor(_number: number) {
    this._number = _number
    var gen = this.generator();
    var curr = gen.next();
    
    while (!curr.done) {
      if(curr.value)
        this._primes.push(Buffer.from(curr.value.toString()))
      curr = gen.next();
    }
}

getPrimes() { 
  return  this._primes 
}

*generator(): IterableIterator<number> {

 /**
 * An integer is prime if it is not divisible by any prime less than or equal to its square root
 **/
  var i = 2;
    if(this._number >= 2 ) {
    
    function isPrime(val: number) {
      for (var i = 2; i <= Math.sqrt(val); i++) {
        if (0 === val % i ) {
          return false;
        }
      }
      return true;
    }

    while(i < this._number) { 
      yield ( isPrime(i))? i: 0 ;
      i++;
    }
    return true;
  }
    return false     
 }



}

and an easy call would get all those primes,

var primeNumbers = new PrimeNumbers(1000)
    console.log(primeNumbers.getPrimes())
Arun Panneerselvam
  • 1,975
  • 1
  • 16
  • 21
0

prime-lib has a well-optimized Sieve of Eratosthenes solution:

const {generatePrimes, stopOnValue} = require('prime-lib');

const i = generatePrimes(); // create infinite prime iterator 
const s = stopOnValue(i, 100); // stop-iterator after reaching 100

const values = [...s]; // 2, 3, 5, ..., 83, 89, 97

P.S. I am the author of prime-lib.

vitaly-t
  • 22,286
  • 10
  • 106
  • 127
0

Already a lot of answers here but I just wanted to point out 2 ways to optimize the solution.

  1. Don't loop all the way up to n, once you hit the square root all numbers above it can no longer be valid.
...
for (let c = 2; c <= Math.sqrt(n); c++) // use square root as upper limit
  1. All primes have to be of the form 6n +- 1, so non primes can immediately be invalidated without any loop. You only ever have to check 6n +- 1 numbers for prime. The exceptions here are 2 and 3 only.
if ((n - 1) % 6 === 0 || (n + 1) % 6 === 0)
  // test for prime
else
  // not prime

Examples:

  • 5 = 6 - 1
  • 7 = 6 + 1
  • 29 = 6(5) - 1
  • 31 = 6(5) + 1
Matriarx
  • 2,959
  • 1
  • 6
  • 19
-1

Was working with prime numbers recently and landed in this page. Here is my working solution using Sieve of Eratosthenes algorithm with 6k ± 1 optimization and ignoring all even and divisors of 5.

Copy and paste the code as html. Prints the 1st 1,000,000 prime numbers in 10 seconds approx.

<!DOCTYPE html>
<HTML>
<HEAD>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<BODY>
<SCRIPT type="text/javascript">
// The largest integer Java natively supports is 2^53-1, so these
// routines are designed to work for *positive* integers up to that.

// Currently the function check does the idiot proof to see only positive
// integers (not too large) are passed to the other routines.

 
// trial_divide(N,max) uses trial division to seek the smallest
// prime divisor of N, returns 0 if none found.


function trial_divide(N,max) {
  // Trial divides the positive integer N by the primes from 2 to max
  // Returns the first prime divisor found, or 0 if none found
  // Note: if N < max^2 is a prime, then N will be returned. 
  if (N%2 == 0) return 2;
  if (N%3 == 0) return 3;
  // No need to go past the square root of our number
  var Stop = Math.min(Math.sqrt(N),max);
  // Okay, lets "wheel factor" alternately adding 2 and 4
  var di=2;
  for(i=5; i<=Stop; i+=di, di=6-di) {
    if (N%i == 0) return i;
  };
  if (N >= max*max) return 0; 
  return N;
}


// modmult(a,b,N) finds a*b (mod N) where a, b, and N can be 
// up to (2^53-1)/2.  Might up this to 2^53-1 eventually...

  function modadd(a,b,N) {
  // When the integers a, b satisfy a+b > 2^53-1, then (a+b)%N is wrong
  // so we add this routine to allow us to reach a, b = 2^53-1.
    if (a+b > 9007199254740991) {
      // Could reduce a and b (mod N) here, but assuming that has already been done
      // won't hurt if not... subtract 2^52 from one, 2^52-1 from the other and the
      // add it back modulo N (MaxInt+1)  
      var t = ( (a-4503599627370496) + (b-4503599627370495) )%N;
      return ( t + (9007199254740991 % N) );
    }
    // Usual case: a + b is not too large:
    return ( (a+b)%N );
  }

function modmult(a,b,N) {
  if (a > N) a = a%N;
  if (b > N) b = b%N;
  if (a*b <= 9007199254740991) {
    return ((a*b)%N);
  } else {
    if (b > a) return modmult(b,a,N);

    // Right to left binary multiplication
    var t = 0;
    var f = a;
    while (b > 1) {
      if ((b & 1) == 1) t = modadd(t,f,N);
      b = Math.floor(b/2);
      f = modadd(f,f,N);
    };
    t = modadd(t,f,N);
    return t;
  }
}

// modpow(a,exp,N) finds a^exp (mod N) where a, b, and N are 
// limited by modmult

function modpow(a,exp,N) {
  if (exp == 0) return 1;

  // Right to left binary exponentiation
  var t = 1;
  var f = a;
  while (exp > 1) {
    if ((exp & 1) == 1) {  // if exponent is odd
      t = modmult(t,f,N);
    }
    exp = Math.floor(exp/2);
    f = modmult(f,f,N);
  };
  t = modmult(t,f,N);
  return t;
}

// SPRP(N,a) checks if N (odd!) is a strong probable prime base a 
// (returns true or false)

function SPRP(N,a) {
  var d = N-1; s = 1;     // Assumes N is odd!
  while ( ((d=d/2) & 1) == 0) s++; // Using d>>1 changed the sign of d!
  // Now N-1 = d*2^s with d odd
  var b = modpow(a,d,N);
  if (b == 1) return true;
  if (b+1 == N) return true;
  while (s-- > 1) {
    b = modmult(b,b,N);
    if (b+1 == N) return true;
  }
  return false;
}

// The idiot proofing, answer returning script

function check(e){
  if (e.hasAttribute("disabled")) return;
  var start = performance.now();
  var TrialLimit = 1300; // Should be bigger, like 10000
  var N = document.getElementById("primenumbercheck").value;
  var Result = "Unknown error";
  var a;
    
  if (N > 9007199254740991) {
    Result = "Sorry, this routine will only handle integers below 9007199254740991.";
  } else if (N == 1) {
    Result = "The number 1 is neither prime or composite (it the multiplicative identity).";
  } else if (N < 1) {
    Result = "We usually restrict the terms prime and composite to positive integers";
  } else if (N != Math.floor(N)) {
    Result = "We usually restrict the terms prime and composite to positive integers";
  } else {
    // Okay, N is of a resonable size, lets trial divide
    window.status = "Trial dividing " + N + " to " + TrialLimit + ".";
    i = trial_divide(N,TrialLimit);
    if (i > 0 && i != N) { 
      Result = N+" is not a prime! It is "+i+" * "+N/i;
    } else if (N < TrialLimit*TrialLimit) {
      Result = N+" is a (proven) prime!";
    } else if ( SPRP(N,a=2) && SPRP(N,a=3) && SPRP(N,a=5) && SPRP(N,a=7) 
      && SPRP(N,a=11) && SPRP(N,a=13) && SPRP(N,a=17)) {
      // Some of these tests are unnecessary for small numbers, but for
      // small numbers they are quick anyway.
      if (N < 341550071728321) {
        Result = N + " is a (proven) prime.";
      } else if (N == 341550071728321) {
        Result = N+" is not a prime! It is 10670053 * 32010157.";
      } else {
        Result = N + " is probably a prime (it is a sprp bases 2, 3, 5, 7, 11, 13 and  17).";
      };
    } else {
      Result = N+" is (proven) composite (failed sprp test base "+a+").";
    };
  };
  var end = performance.now();
  var timeTaken = end - start;
  window.status= "Done!"; // here so says done when present alert box
  var x = document.getElementsByClassName("primecheck");
  x[0].innerHTML = Result;
  setTimer(timeTaken);

}

function generate(e){
  if (e.hasAttribute("disabled")) return;
  var start = performance.now();
  var x = document.getElementsByClassName("primelist");
  var N = document.getElementById("primenumberlist").value;

  var i = 2;
  var Result = "2, ";
  var currentInt = 3;
  var possiblePrime;
  if (N == 2) 
    Result = Result + currentInt + ", ";
  else {
    while (i < N) {
      possiblePrime = false;
        if(currentInt == 3) {
          Result = Result + currentInt + ", ";
            possiblePrime = false;
        }
 else if(currentInt % 5 == 0 && currentInt > 5) {
   possiblePrime = false;
 }
        else if(currentInt % 6 == 1 || currentInt % 6 == 5) 
          possiblePrime = true;
        if(possiblePrime) {
          if(trial_divide(currentInt,Math.ceil(Math.sqrt(currentInt))) == currentInt) {
            Result = Result + currentInt + ", ";
            i++;
          }
        }
        currentInt = currentInt + 2;
      }
    }
  var end = performance.now();
  var timeTaken = end - start;
  x[0].innerHTML = Result.substring(0, Result.length - 2);
  setTimer(timeTaken);
}

function setTimer(timeTaken) {
  var timerElement = document.getElementsByClassName("timeElapsed")[0];
  var timerPreText = "Time Elapsed: ";
  var duration = convertMS(timeTaken);
  timerPreText = timerPreText + duration.day + " days: " + duration.hour + " hours: " + duration.minute + " minutes: " + duration.seconds + " seconds" + ": " + 

duration.milliseconds + " milliseconds";
  timerElement.innerHTML = timerPreText;
}

function isNumberKey(evt)
{
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57))
     return false;
     return true;
}

function convertMS( milliseconds ) {
    var day, hour, minute, seconds, milliseconds;
    seconds = Math.floor(milliseconds / 1000);
    milliseconds = milliseconds - (seconds * 1000);
    milliseconds = milliseconds.toFixed(2);
    minute = Math.floor(seconds / 60);
    seconds = seconds % 60;
    hour = Math.floor(minute / 60);
    minute = minute % 60;
    day = Math.floor(hour / 24);
    hour = hour % 24;
    return {
        day: day,
        hour: hour,
        minute: minute,
        seconds: seconds,
 milliseconds: milliseconds
    };
}

function checkInput(input, buttonId)
{
    var name = input.value;
    var cansubmit = (name.length > 0);
    if (cansubmit) {
        document.getElementById(buttonId).removeAttribute("disabled");
    } else {
        document.getElementById(buttonId).setAttribute("disabled", null);
    }
};

</SCRIPT>

<article class="message is-success timerDiv" style="visibility: visible;">
  <div class="message-body">
    <p class="timeElapsed">Time elapsed will be shown here!</p>
  </div>
</article>

<article class="message is-primary">
  <div class="message-body">
    <strong class="title">Check prime number</strong>
 <div class="content" style="margin-top: 10px;">
 <div><input id="primenumbercheck" class="input is-rounded" type="text" placeholder="Enter the number you wanna check..." style="max-width: 25%;" 

onkeypress="return isNumberKey(event)" onkeyup="checkInput(this, 'primenumbercheckButton')">
 <a class="button is-link is-rounded" onclick="check(this)" id="primenumbercheckButton" disabled>Check</a></div>
 </div>
  </div>
</article>

<div class="container is-fullhd">
  <div class="notification primecheck">
    Prime check goes here!
  </div>
</div>

<article class="message is-primary">
  <div class="message-body">
    <strong class="title">List prime numbers</strong>
 <div class="content" style="margin-top: 10px;">
 <div><input id="primenumberlist" class="input is-rounded" type="text" placeholder="Enter the number of prime numbers you wanna generate..." style="max-width: 

35%;" onkeypress="return isNumberKey(event)" onkeyup="checkInput(this, 'primenumberlistButton')">
 <a class="button is-link is-rounded" onclick="generate(this)" id="primenumberlistButton" disabled>List</a></div>
 </div>
  </div>
</article>

<div class="container is-fullhd">
  <div class="notification primelist">
    Prime list goes here!
  </div>
</div>

</div>

</BODY>
</HEAD>
</HTML>
Eric Stanley
  • 69
  • 2
  • 7