Please write a function in java, that will check a number between 1 and 1000 and return the value 1, if the number is a prime number and return the value 0 otherwise

解决方案 »

  1.   


    方法代码如下: public static int test(int a)
        {  int t; 
         int j;
        
         if(a>=1&&a<=1000)
         {    t=1;
            for(j=a-1;j>=2;j--)
              {
              if(a%j==0)
              { t=0;
              break;
              }
              }
          
            return t;
         }
         else 
             { System.out.println("the number is extending!");
                 return -1;
                }
           
        }
      

  2.   

     import java.io.*; public class test
     {
     int a;
     public  test(int   a) 
     {
     this.a = a;
     }
     public void pri()
     {
     int   t;
     int   j;
     if(a>=1&&a <=1000)
     {
     t=1;
     for(j=2;j<=Math.sqrt((double)a);j++)//只须从2判断到a的正平方根即可
     {
     if(a%j==0)
     {
     t=0;
     break;
     }
     }
     System.out.println(t);
     }
     else
     {
     if(a<1)
    System.out.println("the   number   is   smaller than 1!");
     else
    System.out.println("the   number   is   bigger than 1000!");
     }
    } public static void main(String[] args)
    {
    try
    {
                            //读取控制台输入
    InputStream in = System.in;          
                            //用InputStreamReader目的是,最终能用用BufferedReader来读取一行数据               
    InputStreamReader ins = new InputStreamReader(in);
                            //用BufferedReader来读取一行数据
                            BufferedReader br = new BufferedReader(ins);    
                            //读取一行数据   
                            String S = br.readLine();                             int a = 0;
    int j=S.length();
    int t=1;
                            //将读入的数据从字符型转换为相应的整数
    while(j>0)                                         
                               {
    a+=(S.codePointAt(--j)-48)*t;
    t*=10;
    }
    test te = new test(a);
    te.pri();
    }
    catch (Exception ex)
    {
    ex.printStackTrace();
    }
    }
    }
    代码如下,谢谢一楼,参照了一楼的思想,完善了从控制台输入和优化了素数判断。