JavaScript学习笔记3

版权声明:随意转载,转载请注明出处。 https://blog.csdn.net/qq_36258516/article/details/85778720

JavaScript学习笔记

问题描述(来自廖雪峰官网):

  请尝试用filter()筛选出素数:

'use strict';

function get_primes(arr) {
  //需要补充的部分
}

// 测试:
var
    x,
    r,
    arr = [];
for (x = 1; x < 100; x++) {
    arr.push(x);
}
r = get_primes(arr);
if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
    console.log('测试通过!');
} else {
    console.log('测试失败: ' + r.toString());
}

解题思路:

  函数传递进来的是一个1-100数的数组,返回的是质数数组。可以直接用filter来处理这个数组,再者利用素数的性质筛选(这里就没有用素数筛法)。

代码:

'use strict';

function get_primes(arr) {
    arr=arr.filter(function (x) {
        if(x == 1) return false;/*1既不是素数也不是合数*/
        for(let i=2;i*i<=x;i++) {
            if (x % i === 0) {
                return false;
            }
        }
        return true;
    })
    return arr;
}
// 测试:
var
    x,
    r,
    arr = [];
for (x = 1; x < 100; x++) {
    arr.push(x);
}
r = get_primes(arr);
if (r.toString() === [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97].toString()) {
    console.log('测试通过!');
} else {
    console.log('测试失败: ' + r.toString());
}

猜你喜欢

转载自blog.csdn.net/qq_36258516/article/details/85778720
今日推荐