Search This Blog

Sunday 27 April 2014

Java program to generate odd numbers then pick and display prime numbers among them.

import java.io.*;
public class OddNumber
{

    public static void main(String args[]) throws IOException
    {
               
        int limit;
        int b=0;
  
        DataInputStream in=new DataInputStream(System.in);
        System.out.println("Enter the limit:");
        limit=Integer.parseInt(in.readLine());

        int[] a= new int[50];
        System.out.println("Printing Odd numbers between 1 and " + 

        limit);
        for(int i=1; i <= limit; i++)
        {
            boolean isPrime = true;
            for(int j=2; j < i ; j++)
            {                       
                if(i % j == 0)
                {
                    isPrime = false;
                    break;
                }
            }
            //if the number is not divisible by 2 then it is odd
            if( i % 2 != 0)
            {
                System.out.print(i + " ");
            }
            if(isPrime)
            {
                if(i>2)   //1 is not prime and 2 is even.
                {
                    a[b] =i;
                    b++;
                }
            }
        }
              
        System.out.println("\nPrime numbers are as follows:");
        for(int k=0;k<=b-1;k++)
            System.out.println(a[k]);
      
    }  
}

No comments :

Post a Comment

FREE Hit Counters