Prime Number Generator Logic

后端 未结 15 2319
旧时难觅i
旧时难觅i 2021-01-07 04:10

I am supposed to make a class PrimeNumberGenerator which has a method nextPrime that will print out all prime numbers up to a number the user input

15条回答
  •  难免孤独
    2021-01-07 04:58

    Check this algorithm based on the sieve of Eratosthenes for prime numbers. Of course you need to adapt it to your program.

    boolean isPrime[] = new boolean [N+1];
    for (int i=2; i <=N; i++)
        isPrime[i] = true;
    
    //mark non-primes <=N using Sieve of Eratosthenes
    for (int i=2; i*i<=N; i++) 
    {
        //if is a prime,then mark multiples of i as non prime 
        for (int j=i; i*j<=N; j++) 
        {
            isPrime[i*j] = false;
        }
    }
    
    for (int i=2; i<=N; i++) 
        if (isPrime[i])
            //Do something.......   
    

提交回复
热议问题