Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving the seventh with O(n)

I have solved the seventh problem of Euler, it says:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

I solved it using, and in the array in which I keep the cousins, when it reaches the length of 10001, I return that number. The algorithm takes 1300 ms, which I tink that is very inefficient, what am I doing particularly in my implementation?

var start = performance.now();

function eratosthenes(n) {
  var arr = [2], acc = 0; 
// matrix to save the found prime numbers and mark their multiples
  for(var i = 3; true; i += 2) { // loop
    if(arr.length === n) return arr[arr.length - 1]; // if the array length is equal to n return the last number
    if(!resolve(arr, i)) { // check if is multiple of the prime numbers, already found.
      arr.push(i); // if isnt multiple, save it
    }
  }
}

function resolve(array, n) {
  return array.some(cur => !(n%cur));
}
console.log(eratosthenes(10001)); // Tooks 1300 ms

var end = performance.now();
var time = end - start;

console.log(time);
like image 507
J. Uchu Avatar asked Jan 20 '26 04:01

J. Uchu


2 Answers

Euler sieve, Pham knows this one :) 12ms

Uchu, I don't see where your code is marking the multiples. Isn't that what Sieve of Eratosthenes is supposed to do?

JavaScript code (this code is actually an adaptation of code by btilly, optimizing an idea of mine):

var start = performance.now();
n = 115000
a = new Array(n+1)
total = 0
s = []
p = 1
count = 0
while (p < n){
  p = p + 1

  if (!a[p]){
    count = count + 1
    if (count == 10001){
      console.log(p);
      end = performance.now();
      time = end - start;

      console.log(time);
      break;
    }
    a[p] = true
    s.push(p)

    limit = n / p
    new_s = []

    for (i of s){
      j = i
      while (j <= limit){
        new_s.push(j)
        a[j*p] = true;
        j = j * p
      }
    }
    s = new_s
  }
}
like image 133
גלעד ברקן Avatar answered Jan 21 '26 19:01

גלעד ברקן


As requested by JaromandaX, this is the code for Sieve of Eratosthenes. 51 ms on my browser (OP solution is 750 ms)

var max = 1000000;

function eratosthenes(n) {
   var arr = [], count = 0;
   for (var i = 0; i < max; i++){
   	   arr.push(true);
   }
   for (var i = 2; i < max; i++){
   	   if(arr[i]){
 
   	   	   count++;
   	   	   if(count == n){
 
   	   	   	  return i;
   	   	   } 
   	   	   for (var j = i + i; j < max; j += i ){
   	   	   	    arr[j] = false;
   	   	   }
   	   }
   }
    
}
var start = performance.now(); 
console.log(eratosthenes(10001)); 
var end = performance.now();
var time = end - start;

console.log(time);
like image 26
Pham Trung Avatar answered Jan 21 '26 18:01

Pham Trung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!