re: Write a program or script to find Lucky Numbers VIEW POST


While JavaScript isn't the fastest language out there I got an implementation working as follows: Great challenge!

Finds luck numbers up to 1,000,000 in ~12s


Fine! This runs in about 19s on my Notebook. splice() works in place. filter() generates a copy and is an additional loop. So I thought working out of place with slice() could be better. No way. I didn't even wait for it to end. Your implementation with splice and filter is faster.


Sorry about deleting my comment, I totally broke my code

So I changed the .splice(j-1, 1, 0) to a direct array access and fixed the j offset, making it 2x faster

function getLuckyNumbersTo(n, d=false) {
    const start =;
    let lucky = new Array(n).fill(0).map((v,i) => i+1);
    if (d) console.log(lucky);
    for (let i = 2; i < lucky.length;) {
        for (let j = i; j <= lucky.length; j+=i) {
            lucky[j-1] = 0;
        if (d) console.log(i, => v));
        lucky = lucky.filter(v => v !== 0);
        i = lucky.find(v => v >= i + 1);
    const end =;
    const duration = end - start;
    console.table({ size:n, length:lucky.length, time:duration });
    return lucky;

My goal is to see if I can make a function* Generator but I haven't been able to figure out a consistent pattern yet that can drip out numbers..

code of conduct - report abuse