使用node.js将前100个素数写入文件 [英] Writing first 100 prime numbers to a file using node.js

查看:121
本文介绍了使用node.js将前100个素数写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自学node.js(没有javascript或真正的编程经验)并且遇到了我试图解决的问题之一。我的目标是将前100个素数写入txt文件。以下是我目前的代码。

I am trying to teach myself node.js (no javascript or real programming experience) and have hit a road block on one of the problems I am trying to solve. My goal is to write the first 100 prime numbers to txt file. Below is my code so far.

var fs = require('fs');
var outfile = "test.txt";
var primality = function () {
    var arr = [];
    for (var n = 2; n <= 542; n++) {
        var primeTrue = true;
        for (var i = 2; i <= Math.sqrt(n); i++) {
            if (n % i === 0) {
                primeTrue = false;
            }
        }
        if (primeTrue) {
            arr.push(n);
        }
    }
    return arr;
}
fs.writeFileSync(outfile, arr);

我使用codecademy javascript实验室来测试我的循环和条件,这段代码似乎确实有效。 (这也可能不是最好的方法,因为我必须设置我的计数器停在542而不是让程序停在第100个素数)。无论如何,当我添加

I was using the codecademy javascript lab to test my loop and conditions and this code does seem to work. (It is also likely not the best way to do this since I had to set my counter to stop at 542 rather than have the program stop at the 100th prime number). In any event, when I added

var outfile = "test.txt"

fs.writeFileSync(outfile, arr);

这并没有像我想象的那样将100个素数输出到txt文件。我仍然在学习的基础上,所以我非常感谢您提供的任何帮助。

this did not output the 100 prime numbers to the txt file as I thought it would. I'm still on the ground floor of my learning so I greatly appreciate any help you can provide.

提前谢谢。

Kevin

推荐答案

你在一个功能中做了很多。如果你将它分解为两个函数,一个用于制作素数列表,另一个用于测试特定数字是否为素数,代码可能会更容易理解:

You're doing a lot in one function. The code may be a bit easier to follow if you break it up into two functions, one to make the list of primes and another to test if a specific number is prime:

function listPrimes( nPrimes ) {
    var primes = [];
    for( var n = 2;  nPrimes > 0;  n++ ) {
        if( isPrime(n) ) {
            primes.push( n );
            --nPrimes;
        }
    }
    return primes;
}

function isPrime( n ) {
    var max = Math.sqrt(n);
    for( var i = 2;  i <= max;  i++ ) {
        if( n % i === 0 )
            return false;
    }
    return true;
}

现在你可以在Node中运行它:

Now you can run it in Node:

var fs = require('fs');
fs.writeFileSync( 'test.txt', listPrimes(100) );

或直接在浏览器控制台中:

or directly in the browser console:

listPrimes( 100 );

(我没有在Node中测试代码,只在浏览器中测试。)

(I didn't test the code in Node, only in the browser.)

一些相关的注释:


  1. sqrt()计算在 isPrime()的循环外移动,因此不必为您正在测试的每个数字重新计算。

  2. 无需 542
  1. The sqrt() calculation is moved outside the loop in isPrime(), so it doesn't have to be recalculated for each number you're testing.
  2. The nPrimes variable lets you generate the exact number of primes you want without the 542 hack.

编写这个简单的版本后,看看可能的优化很有意思。一种是仅检查先前生成的素数的可除性,而不是检查直到平方根的所有整数。你可以这样做:

Having written this simple version, it's interesting to look at possible optimizations. One is to check for divisibility only on the previously generated primes, instead of checking all integers up to the square root. You could do that like this:

function listPrimes( nPrimes ) {
    var primes = [];
    for( var n = 2;  nPrimes > 0;  n++ ) {
        if( isPrime( n, primes ) ) {
            primes.push( n );
            --nPrimes;
        }
    }
    return primes;
}

function isPrime( n, primes ) {
    var max = Math.sqrt(n);
    for( var i = 0;  i < primes.length  &&  primes[i] <= max;  i++ ) {
        if( n % primes[i] === 0 )
            return false;
    }
    return true;
}

如果您生成大量素数,这可能会更快,尽管对于其中的100个而言,它几乎不重要,我倾向于坚持使用更简单的代码。

That may be faster if you're generating a large number of primes, although for 100 of them it hardly matters and I'd be inclined to stick with the simpler code.

当然,如果你在谈论优化,那么总是值得考虑一下不同的算法。 Sieve of Eratosthenes 非常有趣,因为它快速,简单且易于理解。维基百科的文章很好地说明了它的工作原理。在JavaScript中它可能看起来像这样:

Of course if you're talking about optimization, it's always worth considering a different algorithm. The Sieve of Eratosthenes is a fun one because it's fast and fairly simple and easy to understand. That Wikipedia article has a great illustration of how it works. In JavaScript it might look something like this:

function listPrimes( max ) {
    // Start with an empty list of primes
    var primes = [];
    // Initialize the sieve - each number is prime unless proven otherwise
    var sieve = new Array( max );
    for( var i = 1;  i <= max;  i++ ) {
        sieve[i] = true;
    }
    // Now check each number from 2 through max
    for( var p = 2;  p <= max;  p++ ) {
        if( sieve[p] ) {
            // p is prime, save it in the output list
            primes.push( p );
            // Mark p * 2, p * 3, p * 4, etc. as non-prime
            for( var t = p * 2;  t <= max;  t += p ) {
                sieve[t] = false;
            }
        }
    }
    return primes;
}

是的,在推荐将代码分成两个函数之后,我现在又回来了一个功能。 : - )

Yes, after recommending splitting the code into two functions, I'm now back to one function. :-)

Sieve的一个不同之处在于你无法真实地说,请给我第一个N素数;相反,你问它,请给我所有低于N的素数。但如果N是一个很大的数字,它比其他方法快得多。

One difference about the Sieve is that you can't really say, "please give me the first N primes"; instead you ask it, "please give me all the primes less than N". But if N is a large number, it is much faster than the other approach.

这篇关于使用node.js将前100个素数写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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