#9754: 同樣寫法用C++可過 但Java逾時 請問如何改進??


xain (賢情逸致)

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

package basic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;

public class a007_1 {
 static boolean[] mark = new boolean[46340 + 1]; // 求使用篩選法求46340以內質數,true非質數
             // false質數

 static long[] prime = new long[4793]; // 46340以內質數有4792個
 static boolean[] base_mod_prime = new boolean[] { false, true, false, true,
   false, true, false, true, false, true };

 public static void main(String[] args) {

  BufferedReader buf = new BufferedReader(
    new InputStreamReader(System.in));

  Scanner cin = new Scanner(System.in);
  int n;
  // ofstream fout("a007-out.txt");
  int j, flag, sq, i = 0;
  make();// 啟動篩選法求質數
  // fout << "i="<<i <<" "<<prime[i] <<endl;

  String text = "";

  try {
   while ((text = buf.readLine()) != "") {

    // long inputn = cin.nextLong();
    long inputn = Long.parseLong(text);
    int modnumber = (int) (inputn % 10);

    // if (n==0) break;
    flag = 0;
    if (inputn <= 9) {
     if (base_mod_prime[modnumber] == false
       ||(modnumber == 1)
       ||(modnumber == 9)) {
      flag = 1;
     }
     
     if (modnumber == 2) {
      flag = 0;
     }
    } else {
     if (base_mod_prime[modnumber]) {
      
      if(inputn<46340){
       if(mark[(int) inputn])
       {
        flag = 1;
       }
      }else{
      
      j = 1;
      long sq1 = (long) Math.sqrt(inputn);
      while (prime[j] <= sq1 && (inputn % sq1!=0)) {
       
       if (((inputn % prime[j]) == 0)) {
        flag = 1;
        break;
       }
       j++;
      }
      }
     } else {
      flag = 1;
     }
    }
    if (flag == 1) {
     System.out.println("非質數");
    } else {
     System.out.println("質數");
    }
   }
  } catch (NumberFormatException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 public static void make() {
  //int sq = (int) Math.sqrt(46340);
  int sq = 46340;
  
  mark[0] = true;// 0不是質數
  mark[1] = true;// 1不是質數
  prime[0]=2;
  int n = 1;
  for (int i = 3; i <= sq; i+=2) {
   if (!mark[i]) {// 將2,3,5...倍數的數皆不是質數
    prime[n] = i;
    n++;
    // fout << i<<" "<<prime[i] <<endl;

    for (int j = i * i; j <= 46340; j += i) {
     mark[j] = true;
    }
   }
  }
  prime[4792] = 0x7fffffff;

 }

 

}

 
ZeroJudge Forum