寻找第一万零一素数 - 项目欧拉 [英] Finding the 10001st Prime Number - Project Euler

查看:235
本文介绍了寻找第一万零一素数 - 项目欧拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到第一万零一素数。我已经看过其他code人写的,但我真的不明白这意味着什么。我曾用JavaScript编写的一些code中,我试图用筛埃拉托色尼中。我不知道是什么问题。它看起来好像它应该正常工作,但我得到了错误的答案。

  VAR计算=功能(){
VAR总理= [2,3,5,7,11,13,17,19];
对于(VAR我= 20; I< = 80000;我++){
如果(我%2 == 0安培;!&安培; I%3 == 0安培;!&安培; I%5 == 0安培;!&安培; I%7 == 0安培;!&安培; I%11! == 0安培;&安培; I%13 == 0安培;!&安培; I%17 == 0安培;!&安培;!I%19 == 0){
 prime.push(ⅰ);
  }
 }
 的console.log(素[10000]);
}; 计算();


解决方案

这是一个简单的方法,但要找到万分之一

(或者在某些机器甚至十万分之一)

你需要超时砍它,

或船吧开了个webworker从锁定保管。

您只需要检查素因子,你收集它们,

因为每一个数字是素数的任何产品

或者其本身就是素数。

 函数nthPrime(第n){
    VAR P = [2],N = 3,DIV,I,限制,isPrime;
    而(P.length<第n){
        DIV = 3,I = 1;
        极限=的Math.sqrt(N)+1;
        isPrime = TRUE;
        而(DIV<限制){
            如果(N%DIV === 0){
                isPrime = FALSE;
                DIV =限制;
            }
            其他的div = P [I ++] || DIV + 2;
        }
        如果(isPrime)P.push(N);
        N + = 2;
    }
    返回P [P.length-1];
}

警报(nthPrime(10001));

I am trying to find the 10,001th prime number. I have looked at other code people have written , but I don't really understand what it means. I have written some code in JavaScript in which I tried to use the Sieve Of Eratosthenes. I'm not sure what the problem is. It looks as if it should work correctly, but I'm getting the wrong answer.

var compute = function() {
var prime = [2,3,5,7,11,13,17,19];
for(var i=20; i<=80000;i++) {
if(i%2!==0 && i%3!==0 && i%5!==0 && i%7!==0 && i%11!==0 && i%13!==0 && i%17!==0 &&      i%19!==0) {
 prime.push(i);
  }
 }  
 console.log(prime[10000]);
};

 compute();

解决方案

This is a simple method, but to find the millionth

(or even hundred thousandth in some machines)

you'll need to chop it up with timeouts,

or ship it off to a webworker to keep from locking up.

You only need to check the prime divisors, as you collect them,

since every number is either the product of primes

or is itself prime.

function nthPrime(nth){
    var P= [2], n= 3, div, i, limit,isPrime;
    while(P.length<nth){
        div= 3, i= 1;
        limit= Math.sqrt(n)+1;
        isPrime= true;
        while(div<limit){
            if(n%div=== 0){
                isPrime= false;
                div= limit;
            }
            else div= P[i++] || div+ 2;
        }
        if(isPrime) P.push(n);
        n+= 2;
    }
    return P[P.length-1];
}

alert(nthPrime(10001));

这篇关于寻找第一万零一素数 - 项目欧拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆