Advertisement
Guest User

Untitled

a guest
Jun 24th, 2016
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(n) {
  2.     // Eratosthenes algorithm to find all primes under n
  3.     var array = [], upperLimit = Math.sqrt(n), output = [];
  4.  
  5.     // Make an array from 2 to (n - 1)
  6.     for (var i = 0; i <= n; i++) {
  7.         array.push(true);
  8.     }
  9.  
  10.     // Remove multiples of primes starting from 2, 3, 5,...
  11.     for (var i = 2; i <= upperLimit; i++) {
  12.         if (array[i]) {
  13.             for (var j = i * i; j <= n; j += i) {
  14.                 array[j] = false;
  15.             }
  16.         }
  17.     }
  18.  
  19.     // All array[i] set to true are primes
  20.     for (var i = 2; i <= n; i++) {
  21.         if(array[i]) {
  22.             output.push(i);
  23.      
  24.         }
  25.      
  26.     }
  27.  
  28.       console.log(Math.max.apply(Math, output));
  29.    
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement