简体   繁体   English

打印素数从2到1000

[英]Printing out Prime Numbers from 2 to 1000

I am writing a code that write all the prime numbers from 2 to 1000 in a file, named primes.txt. 我正在写一个代码,将2到1000之间的所有素数写入一个名为primes.txt的文件中。 For some reason I am not able to figure out the correct way to do this problem. 由于某种原因,我无法找出解决此问题的正确方法。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Problem6 {

    /**
     * @param args
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter prw = new PrintWriter("primes.txt");
        for (int i = 2; i <= 1000; i++){
            if (checkIfPrime(i) == true){
                System.out.println(i);
                prw.println(i);
            }
        }
    }

    public static boolean checkIfPrime (int num){
        boolean isPrime = true;  
        for (int i = 2; i <= 1000; i++){
            if ( num % i == 0 ){
                isPrime = false;
            }
        }

        return isPrime;
    }
}

I just dont know what to do... Please help Thanks! 我只是不知道该怎么办...请帮助谢谢!

What happens when you pass in your first number, 2 , to checkIfPrime ? 当您将第一个数字2传递给checkIfPrime时会发生什么? It will take remainder of 2 divided by 2, which is 0, falsely claiming that 2 is not prime. 它将2的余数除以2(即0),错误地声称2不是素数。

You need to stop testing remainders before you actually get to num . 在实际达到num之前,需要停止测试余数。 Stop your i for loop before i gets to num . i进入num之前,请停止i for循环。 (In fact, you can stop after i has reached the square root of num ). (实际上,您可以在i达到num平方根后停止)。

for (int i = 2; i < num; i++){

or even 甚至

for (int i = 2; i <= Math.sqrt(num); i++){

If you're feeling adventurous, you may try implementing the Sieve of Eratosthenes , which marks all composite numbers up to an arbitrary limit (in this question, 1000). 如果您喜欢冒险,可以尝试实现Eratosthenes筛网 ,该筛网将所有复合数字标记为任意限制(在此问题中为1000)。 Then you just print out the rest of the numbers -- the primes. 然后,您只需打印其余数字-质数。

calculation can be made even faster by checking the division with prime numbers only. 通过仅检查质数除法可以更快地进行计算。 Any non prime number is divisible by some prime number smaller than itself. 任何非质数都可以被小于其本身的质数整除。

    static List<Integer> primes = new ArrayList<Integer>();

public static void main(String[] args) {
    for (int i = 2; i < 10000; i++) {
        if(checkPrime(i)){
            primes.add(i);
        }
    }
    System.out.println(primes);
}

private static boolean checkPrime(int n) {
    for (Integer i : primes) {
        if(i*i > n ){
            break;
        }else if(n%i==0 )
            return false;
     }
    return true;
}

Change your for condition in checkIfPrime(int num) to checkIfPrime(int num) for条件更改for

for (int i = 2; i < num; i++) {

BTW if (checkIfPrime(i) == true){ can be written as if (checkIfPrime(i)){ 顺便说一句if (checkIfPrime(i) == true){可以写成if (checkIfPrime(i)){

A number num is prime if it's not divisible by any other number that is greater than one and smaller than num . 如果数字num不能被大于1 且小于num其他数字整除,则它是质数。 Where is this in your code? 您的代码在哪里? :-) :-)

Here's how you could "hard-code" an incremental sieve of Eratosthenes on a 2-3-5-7 wheel to print the primes up to 1000 . 您可以按照以下方法2-3-5-7轮 “硬编码” Eratosthenes增量筛,以打印多达1000的质数。 In C-like pseudocode , 类似C的伪代码中

primes_1000()
{
   // the 2-3-5-7 wheel
   int wh[48] = {10,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,
                  2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2};
   // core primes' multiples, each with its pointer into the wheel
   int m[7][4] = { {1,11,11,11*11}, {2,13,13,13*13}, {3,17,17,17*17},
                   {4,19,19,19*19}, {5,23,23,23*23}, {6,29,29,29*29},
                   {7,31,31,31*31} };    // 23*23 = 529 
   int i=1, p=11, k=0;
   print(2); print(3); print(5); print(7);
   p = 11;             // first number on the wheel - the first candidate
   do {
      // the smallest duplicate multiple is 121*13, ==> no dups below 1000!
      for( k=0; k < 7; ++k) {
         if ( p == m[k][3] ) {             // p is a multiple of m[k][1] prime:
            m[k][2] += wh[ m[k][0]++ ];    //   next number on the wheel
            m[k][3]  = m[k][1] * m[k][2];  //   next multiple of m[k][1] 
            m[k][0] %= 48;                 //   index into the wheel
            break;
         }
      }
      if (k == 7) {    // multiple of no prime below 32 -
          print(p);    //   - a prime below 1000!   (32^2 = 1024)
      }
      p += wh[i++];    // next number on the candidates wheel
      i %= 48;         // wrap around to simulate circular list
   } while ( p < 1000 );
}

For primes below 500 , only 4 sieve variables need to be maintained, for the additional core primes {11,13,17,19} above the wheel's inherent primes 2,3,5,7 . 对于小于500的素数,仅需维护4个筛网变量,对于车轮固有质数2,3,5,7上方的附加芯素数{11,13,17,19}

(see also Printing prime numbers from 1 through 100 ). (另请参阅打印从1到100的质数 )。

m is the dictionary of base primes and their multiples on the wheel ( multiplesOf(p) = map( multiplyBy(p), rollWheelFrom(p) ) , each with its own index into the wheel. It should really be a priority queue, min-ordered by the multiples' values. m是轮子上基本质数及其倍数的字典( multiplesOf(p) = map( multiplyBy(p), rollWheelFrom(p) )multiplesOf(p) = map( multiplyBy(p), rollWheelFrom(p) ) ,每个素数都有其在轮子上的索引。它实际上应该是一个优先级队列min -按倍数的值排序。

For a true unbounded solution a separate primes supply can be maintained, to extend the dictionary prime by prime when the next prime's square is reached among the candidates. 对于真正的无界解决方案,可以维持单独的素数供给 ,以便在候选项中达到下一个素数平方时逐个素数扩展字典素数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM