简体   繁体   English

Java的eratosthenes问题筛

[英]Sieve of eratosthenes problem java

I am trying to make sieve of eratosthenes, i am currently having a problem. 我正在尝试过滤橡皮擦,目前有问题。 The probelm is that during the calculation method, the program won't continue to the next prime number. 问题是在计算方法期间,程序将不会继续到下一个素数。 I think the problem is with the while loop but i don't know how to fix it. 我认为问题出在while循环上,但我不知道如何解决。 Can someone help me? 有人能帮我吗?

Thank you 谢谢

import java.util.*;
import java.io.*;

public class Primes_below_N {

    static Vector<Integer> numbers = new Vector<Integer>();
    static BufferedReader br = new BufferedReader(new InputStreamReader(
            System.in));

    public static void main(String[] args) throws IOException {
        System.out.print("Please enter a number: ");
        int LIMIT = Integer.parseInt(br.readLine());
        populate(LIMIT);
        calculatePrimes(LIMIT);
        print(numbers);

    }

    // populate a 'numbers' with a numbers upto limit
    public static void populate(int limit) {
        for (int i = 1; i <= limit; i++) {
            numbers.add(i);
        }
    }

    // calculate prime numbers
    public static void calculatePrimes(int limit) {
        int p = 2;
        int nextPrime = 1;
        while (Math.pow(p, 2) < limit) {
            for (int i = 0; i < numbers.size(); ++i) {
                if (numbers.get(i) % 2 == 0 && numbers.get(i) != i) {
                    numbers.remove(i);
                }
            }
            p = numbers.get(nextPrime);
            nextPrime += 1;
        }
    }

    public static void print(Vector<Integer> list) {
        for (int i : list) {
            System.out.println(i);
        }
    }

}

The problem is with these two line: 问题在于这两行:

  • if (numbers.get(i) % 2 == 0 && numbers.get(i) != i)

It should be if (numbers.get(i) % p == 0 && numbers.get(i) != p) 应该是if (numbers.get(i) % p == 0 && numbers.get(i) != p)

  • p = numbers.get(nextPrime); nextPrime += 1;

The order should be reverse ie nextPrime++; p = numbers.get(nextPrime); 顺序应该相反,即nextPrime++; p = numbers.get(nextPrime); nextPrime++; p = numbers.get(nextPrime);

Also as a side note: the algorithm says to Create a list of consecutive integers from two to n: (2, 3, 4, ..., n) and not from (1, 2, .... , n) 另请注意:该算法表示要创建一个从2到n:(2,3,4,...,n)而不是(1,2,....,n) 的连续整数列表。


I have taken an exact copy of your code and changed the lines which I have mentioned earlier (Marked as CHANGE 1 & CHANGE 2). 我已经复制了您的代码,并更改了我之前提到的行(标记为CHANGE 1和CHANGE 2)。

package test;

import java.util.*;
import java.io.*;

import java.util.*;
import java.io.*;

public class Primes_below_N {

    static Vector<Integer> numbers = new Vector<Integer>();
    static BufferedReader br = new BufferedReader(new InputStreamReader(
            System.in));

    public static void main(String[] args) throws IOException {
        System.out.print("Please enter a number: ");
        int LIMIT = Integer.parseInt(br.readLine());
        populate(LIMIT);
        calculatePrimes(LIMIT);
        print(numbers);

    }

    // populate a 'numbers' with a numbers upto limit
    public static void populate(int limit) {
        for (int i = 1; i <= limit; i++) {
            numbers.add(i);
        }
    }

    // calculate prime numbers
    public static void calculatePrimes(int limit) {
        int p = 2;
        int nextPrime = 1;
        while (Math.pow(p, 2) < limit) {
            for (int i = 0; i < numbers.size(); ++i) {

                // CHANGE 1 - IF block change
                if (numbers.get(i) % p == 0 && numbers.get(i) != p) {
                    numbers.remove(i);
                }
            }

            // CHANGE 2 - Reorder
            nextPrime += 1; 
            p = numbers.get(nextPrime);

        }
    }

    public static void print(Vector<Integer> list) {
        for (int i : list) {
            System.out.print(i + ", "); // Changed for single line printing
        }
    }

}

Test1 测试1

>>Input: Please enter a number: 50 >>输入: Please enter a number: 50

>>Output: 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, >>输出: 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,

One is coming because of your code. 因为您的代码,一个即将到来。

Test2 测试2

>>Input: Please enter a number: 100 >>输入: Please enter a number: 100

>>Output: 1, 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, >>输出: 1, 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,

As you can see for 100 there are 25 prime numbers (excluding 1) 如您所见,有100 素数有25个 (不包括1个)

I looks like you missed a few points on the algorithm. 我好像您错过了算法上的几点。 At face value I'd guess that code is NEVER going to return. 从表面上看,我猜代码永远不会返回。 WHILE p squared is less than limit DO foreach entry in the list... Nope, never... well not in the lifetime of the universe anyway. 虽然p平方小于列表中每个条目的DO限制...不,永远不会...不管怎样,这都不适合宇宙的寿命。

Have a good read through the wikipedia article on the Sieve of Erastothenes: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes . 仔细阅读Erastothenes筛上的Wikipedia文章: http : //en.wikipedia.org/wiki/Sieve_of_Eratosthenes It's even got a great visualisation which SHOWS you how the algorithm works. 它甚至具有出色的可视化效果,可向您展示算法的工作原理。

One issue you will need to address is that as you are applying the sieve, you're removing elements from numbers , and so the indices i and nextPrime aren't pointing where you think they're pointing. 您需要解决的一个问题是,在应用筛子时,您正在从numbers删除元素,因此索引inextPrime并未指向您认为它们指向的位置。 It might help you to print console output to the effect 它可以帮助您将控制台输出打印到效果

System.out.println("Loop index: " + i);

at the beginning of the for loop, and also 在for循环的开始,以及

System.out.println("Got prime: " + p);

right after getting the prime. 在拿到黄金之后

It sounds like you're looking for just a hint, so I'll leave it at that. 听起来您只是在寻找一个提示,所以我将其保留。

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

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