រកចំនួនបឋមក្នុង Java Programming

Below is a function using Java Programming to generate prime number from 2 to n.
For example:
If n=10 then prime number will be 2, 3, 5, 7
In this function prime numbers will return as a list (array).


int[] getPrimeNumber(int n)
        {     
            int x[]=new int[n];
            int j=0;
            boolean isPrime=true;
            
            for(int i=2; i<=n;i++)
            {
                    if(i==2||i==3)
                    {
                        isPrime=true;
                    }
                    else{
                        isPrime=true;
                        for(int k=0; k<j; k++)
                        {                    
                                if(i%x[k]==0)
                                {
                                isPrime=false;
                                break;
                                }
                        }
                    }

                    if(isPrime==true)
                    {
                        x[j]=i;
                        j+=1;
                    }
            }

            int [] vals;
            vals=new int[j];
            System.arraycopy(x, 0, vals, 0, j);

            System.out.println("Show prime number less than "+n);
        
            return vals;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: