JSFiddle - React, Tailwind, and code Playground

by tara5

JavaScript

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

function getStep(list, currentStep) {
    var step = 0,
        currentStep = currentStep || 0;
    
    for (var i = 0; i < list.length; i++) {
        if((list[i] != 0) && (list[i] > currentStep)){
            step = list[i];
            break;
        }
    }
    
    return step;
}

function returnPrimes(num) {
    var list = generateList(num),
        search = true,
        result = [],
        step = getStep(list);
    
    var currentIndex = 0;
    
    while(search) {
        
        currentIndex = list.indexOf(step);
        
        for(var i = currentIndex + step; i < list.length; i += step){
            if((list[i] != undefined) && (list[i] != 0)){
                list[i] = 0;
            }
        }
        
        step = getStep(list, step);
        if(step*step > list.length){
            search = false;
        }
    }
    
    for(var j = 0; j < list.length; j++) {
        if(list[j] !== 0){
            result.push(list.slice(j, j+1)[0]);
        }
    }
    
    return result;
}

var primes = returnPrimes(2000000),
    sum = 0;


for(var j = 0; j < primes.length; j++) {
    sum += primes[j];
}

console.log(sum);