简体   繁体   English

埃拉托色尼的筛子 java

[英]sieve of eratosthenes java

I am trying to write a program that implements the sieve of eratosthenes.我正在尝试编写一个实现埃拉托色尼筛法的程序。 I can get it from 2 to any given end number but the assignment we are working on asks that we input the starting value.我可以从 2 到任何给定的结束编号,但我们正在处理的任务要求我们输入起始值。 I am completely stuck.我完全被困住了。 I've tried many different codes but it keeps giving me weird answers.我尝试了许多不同的代码,但它一直给我奇怪的答案。

My start is the starting value and end is the ending value.我的开始是起始值,结束是结束值。 I basically want to find the prime of this range.我基本上想找到这个范围的素数。 Thank you!!!谢谢!!!

    public static void sieve(int start, int end) {
    int size=(end-start)+1;
    boolean result[]=new boolean[size];
    int prime[]=new int[size];

    for(int i=0; i<size; i++) {
        prime[i]=start+i;
    }


    for(int i=0; i<size; i++) { //every number in result is true
        result[i]=true;
    }

    for(int p=2; p*p <size; p++) {
        if(result[p]==true) {
            for(int i=p*2; i<size; i +=p) {
                result[i]=false;
            }
        }

        for(int i=2; i<size; i++) {
            if(result[i]==true) {
                System.out.print(prime[i] + " ");

            }
        }
    }
}

The Sieve of Eratosthenes works by marking as not prime the multiples of each prime, starting with the first prime number, 2. Eratosthenes的筛网的工作方式是将每个素数的倍数标记为不是素数,从第一个素数2开始。

Therefore, even if you are required to find the primes between start and end , you still have to find all the primes between 2 and end . 因此,即使您需要在startend之间找到素数,您仍然必须在2和end之间找到所有素数。 After you do that, just output the primes within the requested range. 之后,只需输出要求范围内的素数即可。

public class To_find_a_prime_number_using_sieve_of_Eratosthenes { 
    public static void main(String args[]){

        int end_number;
        int arr[];
        arr=new int[100];
        Scanner S=new Scanner(System.in); 
        System.out.println("enter the end number which you want to print he prime number"); 
        end_number=S.nextInt(); 
        //adding natural numbers in the array
        for(int i=0;i<end_number;i++)
        {
            arr[i]=i;
        }
        for(int k=2;k<end_number;k++)
        {

            for(int l=2;l<end_number;l++)
            {
                if(arr[k]*l>end_number)
                { 
                    break; 
                } 
                else {
                    arr[arr[k]*l]=0;
                }

            }

        }

        for(int j=1;j<end_number;j++)
        {
            if(arr[j]!=0 && arr[j]!=1)
            {
                System.out.println(arr[j]); 
            } 
        }
    }
}

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

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