#8590: 逾時...請問這樣怎麼修改?


xain (賢情逸致)

學校 : 國立高雄第一科技大學
編號 : 38637
來源 : [36.235.149.106]
最後登入時間 :
2022-11-29 22:32:50
a007. 判斷質數 | From: [118.170.193.130] | 發表日期 : 2014-01-29 23:34

/**********************************************************************************/
/*  Problem: a007 "判斷質數"                                                  */
/*  Language: JAVA (1647 Bytes)                                                   */
/*  Result: TLE(6s) judge by this@ZeroJudge                                       */
/*  Author: xain at 2014-01-29 23:32:07                                           */
/**********************************************************************************/


package basic;

import java.util.ArrayList;
import java.util.Scanner;

public class a007_1 {
 static ArrayList<Long> alist = new ArrayList<Long>();

 /**
  * @param args
  */

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner cin = new Scanner(System.in);

  makePrimer();

  // 2147483648
  while (cin.hasNext()) {
   long n = cin.nextLong();

   long sqr = (long) Math.sqrt(n);

   for (int i = 0; alist.get(i) <= sqr && i < alist.size(); i++) {
    if (n % alist.get(i) == 0) {
     System.out.print("非");
     break;
    }

   }
   System.out.println("質數");

  }
 }

 private static void makePrimer() {
  alist = new ArrayList<Long>();
  alist.add((long) 2);
  alist.add((long) 3);
  alist.add((long) 5);
  alist.add((long) 7);
  alist.add((long) 11);
  alist.add((long) 13);

  // 2147483648
  // 46341
  long indx = 1;

  while ((long) (indx++) <= 7725) {

   // int d61 = (int) ((a - 1) / 6);
   // int d65 = (int) ((a - 5) / 6);
   long cd61 = (6 * indx + 1);
   long cd65 = (6 * indx + 5);
   long sqr = (long) Math.sqrt(cd65);
   
   long a = cd61;
   boolean isPrimes = true;

   for (int i = 0; alist.get(i) <= sqr && i < alist.size(); i++) {
    if ((a % alist.get(i)) == 0) {
     isPrimes = false;
     break;
    }
   }
   if (isPrimes) {
    alist.add(a);
   }

   a = cd65;
   isPrimes = true;

   for (int i = 0; alist.get(i) <= sqr && i < alist.size(); i++) {
    if ((a % alist.get(i)) == 0) {
     isPrimes = false;
     break;
    }
   }
   if (isPrimes) {
    alist.add(a);
   }

  }

 }

}

 
ZeroJudge Forum