#9619: JAVA這樣寫還是TLE


coder1250 (coder1250)


import java.util.Scanner;
import java.math.*;

public class JAVA {
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  int a;
  int i,j,n=0;
  String f;
  while(input.hasNext()) 
  {
   f="true";
   a=input.nextInt();
   for(i=2;i<=Math.sqrt(a);i++)
   {
    
    if(a%i==0 && a!=2)
    {
     f="false";
     System.out.println("非質數");
     break;  
    }
   }
   if(f=="true")
   {
    System.out.println("質數");
   }

  }
 }
}

#9621: Re:JAVA這樣寫還是TLE


tomoyaken14 (歐練)


import java.util.Scanner;
import java.math.*;

public class JAVA {
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  int a;
  int i,j,n=0;
  String f;
  while(input.hasNext()) 
  {
   f="true";
   a=input.nextInt();
   for(i=2;i<=Math.sqrt(a);i++)
   {
    
    if(a%i==0 && a!=2)
    {
     f="false";
     System.out.println("非質數");
     break;  
    }
   }
   if(f=="true")
   {
    System.out.println("質數");
   }

  }
 }
}

 

 

在測資非常多筆的時候 

輸入可以考慮不要使用Scanner

輸出也可以再加快

 

#9622: Re:JAVA這樣寫還是TLE


nwgs524513cja (無名)


import java.util.Scanner;
import java.math.*;

public class JAVA {
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  int a;
  int i,j,n=0;
  String f;
  while(input.hasNext()) 
  {
   f="true";
   a=input.nextInt();
   for(i=2;i<=Math.sqrt(a);i++)
   {
    
    if(a%i==0 && a!=2)
    {
     f="false";
     System.out.println("非質數");
     break;  
    }
   }
   if(f=="true")
   {
    System.out.println("質數");
   }

  }
 }
}

 

 

在測資非常多筆的時候 

輸入可以考慮不要使用Scanner

輸出也可以再加快

 


題目已經提示你建立質數表,你的寫法每次都到重新計算,肯定無法通過20萬筆測資的壓力測試。

#9626: Re:JAVA這樣寫還是TLE


highcollege90027 (冰人雪糕)


import java.util.Scanner;
import java.math.*;

public class JAVA {
 public static void main(String[] args)
 {
  Scanner input = new Scanner(System.in);
  int a;
  int i,j,n=0;
  String f;
  while(input.hasNext()) 
  {
   f="true";
   a=input.nextInt();
   for(i=2;i<=Math.sqrt(a);i++)
   {
    
    if(a%i==0 && a!=2)
    {
     f="false";
     System.out.println("非質數");
     break;  
    }
   }
   if(f=="true")
   {
    System.out.println("質數");
   }

  }
 }
}

 


先建表 >

 

StringBuffer >

BufferedReader >

這樣會比較快,

你的質數演算也可以先捨棄偶數,

從奇數開始 += 2 上限到你的sqrt,

有解