Thursday 18 July 2013

Prime no in an Efficient Way for ICSE students.....

import java.io.*;
class csk123
{
 public static void main(String args[]) throws IOException
 {
    int n,i;
    DataInputStream in=new DataInputStream(System.in);

    System.out.print("Enter a no:");
    n=Integer.parseInt(in.readLine());


    for(i=2;i<=n/2;i++)
     {
      if(n%i==0)
       break;     
     }

       if(i==(n/2+1))
        System.out.print("Prime");
       else
        System.out.print("not prime");

 }
}


copy and paste ......this program run very much faster than older one, bcoz the loop execute less number of times than the older prime program(from 2 to n/2 instead of 1 to n), sometimes  loop does not execute upto n/2 bcoz of break statement...I will discuss the logic in the class....

4 comments: