Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

sieve of eratosthenes java

// Java program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
 
class SieveOfEratosthenes
{
    void sieveOfEratosthenes(int n)
    {
        // Create a boolean array "prime[0..n]" and initialize
        // all entries it as true. A value in prime[i] will
        // finally be false if i is Not a prime, else true.
        boolean prime[] = new boolean[n+1];
        for(int i=0;i<=n;i++)
            prime[i] = true;
         
        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }
         
        // Print all prime numbers
        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                System.out.print(i + " ");
        }
    }
     
    // Driver Program to test above function
    public static void main(String args[])
    {
        int n = 30;
        System.out.print("Following are the prime numbers ");
        System.out.println("smaller than or equal to " + n);
        SieveOfEratosthenes g = new SieveOfEratosthenes();
        g.sieveOfEratosthenes(n);
    }
}
 
// This code has been contributed by Amit Khandelwal.
Comment

PREVIOUS NEXT
Code Example
Java :: join array java 
Java :: java add commas to numbers 
Java :: servlet redirect java 
Java :: SpEL define default 
Java :: internet permission in android studio 
Java :: set fontcolor of jframe 
Java :: java uuid from string 
Java :: how to convert object to list in java 
Java :: init cap java 
Java :: cannot lock java compile cache as it has already been locked by this process 
Java :: testing if editText is empty java 
Java :: javax notblank not working 
Java :: java how to get deltaTime 
Java :: javaee jsp convert int to string 
Java :: glide latest version android 
Java :: how to clear stringbuilder in java 
Java :: java contains password input 
Java :: javaee .jsp get value of object with EL 
Java :: How to generate all possible k combinations of numbers between 1 and n, in Java? 
Java :: W/System.err: java.io.IOException: Cleartext HTTP traffic to not permitted 
Java :: Bukkit debug message 
Java :: toString convert to long 
Java :: Could not identify launch activity: Default Activity not found 
Java :: Java program to find the sum of all even numbers from 1 to 10 
Java :: convert char to string java 
Java :: programmation android avoir acces à la liste des instants de partage 
Java :: how to create textview programmatically in android 
Java :: java get unix timestamp 
Java :: spring mvc get all request parameters 
Java :: how to iterate over a string in java 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =