SETHA SITE INFORMATION

  • Increase font size
  • Default font size
  • Decrease font size

How to Get Prime Number less than [n]?

E-mail Print PDF
This article shows a function that produce a set of prime numbers less number [n] in Java Programming. The function will return prime numbers in an array.
For example:
- If n=10 then prime number will be 2, 3, 5, 7
- If n=20 then prime number will be 2, 3, 5, 7, 11, 13, 17, 19

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;
}