寻找第一万零一素数

编程入门 行业动态 更新时间:2024-10-21 13:35:52
本文介绍了寻找第一万零一素数 - 项目欧拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图找到第一万零一素数。我已经看过其他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));

更多推荐

寻找第一万零一素数

本文发布于:2023-11-29 20:37:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647561.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:素数   一万

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!