Friday, August 19, 2011

Java Program to display prime numbers from a group of numbers added to a LinkedList

The Program given below adds the given numbers to a linked list,checks if each of them is prime and displays prime numbers.
 import java.io.*;  
 class node  
 {  
   int data;  
   node next;  
   node(int d)  
   {  
     data=d;  
     next=null;  
   }  
   int display()  
   {  
     return(data);  
   }  
 }  
 class list  
 {  
   node first=null;  
   void insert(int d)  
   {  
     node n1=new node(d);  
     node curr;  
     curr=first;  
     if(curr==null)  
       first=n1;  
     else  
     {  
       n1.next=first;  
       first=n1;  
     }  
   }  
   void display()  
   {  
     node curr;  
     curr=first;  
     while(curr!=null)  
     {  
       int e=curr.display();  
       System.out.print(" "+e);  
       curr=curr.next;  
     }  
   }  
  }  
 public class JavaApplication2   
 {  
   public static void main(String[] args)   
   {  
     DataInputStream get=new DataInputStream(System.in);  
     int c,i,a,n,f;  
     node curr1;  
     list l1=new list();  
     list l2=new list();  
     try  
     {  
      System.out.println("Enter the limit");  
      n=Integer.parseInt(get.readLine());  
      System.out.println("Enter the nos:");  
      for(i=0;i<n;i++)  
      {   
        c=Integer.parseInt(get.readLine());  
        l1.insert(c);  
      }  
      curr1=l1.first;  
      while(curr1!=null)  
      {  
        a=curr1.data;        
        f=0;  
        for(i=2;i<(a/2);i++)  
        {  
          if(a%i==0)  
          {  
            f=1;  
            break;  
          }    
        }  
       if(f==0)  
        l2.insert(a);  
       curr1=curr1.next;  
      }  
      System.out.println("Prime nos are:");  
      l2.display();  
     }  
     catch(Exception e)  
     {  
       System.out.println(e.getMessage());  
     }  
   }  
 }  

No comments:

Post a Comment

Which is the Best Photo Watermarking Software

Photo Theft is becoming more and more common in the web with the outburst of social websites like Facebook,Google Plus and Image sharing se...