质数 JavaScript

Prime Numbers JavaScript(质数 JavaScript)
本文介绍了质数 JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指导我在这里获取质数吗?这是家庭作业,所以我不想要答案,但我们将不胜感激.真的很烦我:(

Can someone please give me guidance on getting the primenumbers here? This is homework so I don't want the answer but some pointers would be greatly appreciated. It's really annoying me :(

我想我已经接近了.但我遇到的这个问题是数字 25 和 35.这些不是素数,但这个函数正在返回它们

I think I'm close. But this problems I have are number 25 and 35. These are not prime but this function is returning them

var getPrimeNumber = function(n) {
    if(n === 1) return "";
    else if(n == 2) return 2;
    else if(n == 3) return 3;
    else { 
        for(i=Math.floor(Math.sqrt(n)); i>=2; i--){
            //console.log(i);//maybe another var in here? 
            if(n%i !==0 && n%2 !==0 && n%3 !== 0)
                return n; // 25/Math.sqrt(25) will be equal to zero this is what gives me 25 !!!   
        } 
    }
};

推荐答案

基于本页,这将是一种确定数字是否为素数的方法:

Based on this page, this would be a method for determining if a number is a prime number:

function isPrime(number) {
    let start = 2;
    const limit = Math.sqrt(number);
    while (start <= limit) {
        if (number % start++ < 1) return false;
    }
    return number > 1;
}

node.js 中,确定 2 到 100.000 之间的质数大约需要 250 毫秒.

In node.js it takes about 250Ms for determining the prime numbers between 2 and 100.000.

另见...

[编辑八月.2021] 一个更有效的函数.查看这个 Stackblitz 项目

[edit aug. 2021] A somewhat more efficient function. See this Stackblitz project

document.querySelector(`pre`).textContent = `Prime numbers < 100
` +
  [...Array(100)]
  .map((v, i) => isPrime(i) ? i : 0)
  .filter(v => v > 0)
  .join(`
`);

function isPrime(number) {
  const checkPrime = (nr, limit) => {
    for (let start = 3; start <= limit; start += 2) {
      if (0 === nr % start) {
        return false;
      }
    }

    return nr > 1;
  };

  return number === 2 || number % 2 !== 0 && checkPrime(number, Math.sqrt(number));
}

<pre></pre>

这篇关于质数 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)