計算素數(質數)java演算法(應該是篩法)

來源:互聯網
上載者:User

我的機器 計算到了  14988613   30秒內 

源碼如下:

package com.prime; </p><p>import java.io.BufferedOutputStream;<br />import java.io.BufferedWriter;<br />import java.io.FileOutputStream;<br />import java.util.Date; </p><p>public class Prime { </p><p> protected static final int BUFFER_SIZE = 16 * 1024;<br /> public BufferedWriter bfWriteFile = null;<br /> private static String pathFile = "d://Prime//index.txt";<br /> private static String path = "D://Prime//";<br /> static String crlf = System.getProperty("line.separator"); </p><p> /**<br /> * @param args<br /> */<br /> public static void main(String[] args) {<br /> long l1 = System.currentTimeMillis();<br /> System.out.println("開始:" + new Date(l1).toLocaleString() ); </p><p> int N = 15000000; </p><p> int[] sieve = new int[N + 1];<br /> int i = 0;<br /> for (i = 2; i <= N; i++)<br /> sieve[i] = 1;<br /> for (i = 2; i <= N / 2; i++)<br /> sieve[i * 2] = 0;<br /> int p = 2;<br /> while (p * p <= N) {<br /> p = p + 1;<br /> while (sieve[p] == 0)<br /> p++;<br /> int t = p * p;<br /> int s = 2 * p;<br /> while (t <= N) {<br /> sieve[t] = 0;<br /> t = t + s;<br /> }<br /> } </p><p> String s = "";<br /> int j = 0;<br /> try {<br /> BufferedOutputStream out = null;<br /> out = new BufferedOutputStream(new FileOutputStream(pathFile, true), BUFFER_SIZE); </p><p> for (i = 2; i <= N; i++) {<br /> if (i % 100 == 0)s += crlf;<br /> if (sieve[i] != 0) {<br /> j++;<br /> s += i + ",";<br /> if (j % 1000 == 0) {<br /> if(j % 10000 == 0){<br /> out.close();<br /> out = new BufferedOutputStream(<br /> new FileOutputStream(path + "index_" + j + ".txt" , true), BUFFER_SIZE);<br /> } </p><p> out.write(s.getBytes());<br /> s = "";<br /> System.out.println(i);<br /> }<br /> }<br /> }<br /> out.close();<br /> } catch (Exception e) {<br /> // TODO: handle exception<br /> } </p><p> long l2 = System.currentTimeMillis();<br /> System.out.println("結束:" + (new Date(l2)).toLocaleString());<br /> System.out.println(":" + (l2 -l1));<br /> }<br />}<br />

 

 

 

計算結果:

http://download.csdn.net/source/1468585

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.