xoxama

Primes to N

Apr 23rd, 2020
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Primes to N
  2.  
  3. const input = ['24'];
  4. const print = this.print || console.log;
  5. const gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
  6.  
  7. const N = +gets();
  8. const arrN = [];
  9. const arrPrimes = [];
  10.  
  11. function isPrime(n) {
  12.   if (n === 1) {
  13.     return true;
  14.   } else if (n === 2) {
  15.     return true;
  16.   } else {
  17.     for (var i = 2; i <= Math.sqrt(n); i++) {
  18.       if (n % i === 0) {
  19.         return false;
  20.       }
  21.     }
  22.     return true;
  23.   }
  24. }
  25.  
  26. if (N >= 1 && N <= 1024) {
  27.   for (let i = 1; i <= N; i++) {
  28.     arrN.push(i);
  29.   }
  30.   for (let i = 0; i < arrN.length; i++) {
  31.     if (isPrime(arrN[i]) === true) {
  32.       arrPrimes.push(arrN[i]);
  33.     }
  34.   }
  35. }
  36.  
  37. print(arrPrimes.toString().replace(/,/g, ' '));
Advertisement
Add Comment
Please, Sign In to add comment