Java 素數 prime numbers-LeetCode 204

來源:互聯網
上載者:User

標籤:

Description:

Count the number of prime numbers less than a non-negative number, n

click to show more hints.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

求n以內的所有素數,以前看過的一道題目,通過將所有非素數標記出來,再找出素數,代碼如下:

 1     public int countPrimes(int n) { 2         if (n == 0 || n == 1 || n == 2) 3             return 0; 4         int[] flag = new int[n]; 5         for (int i = 2; i < Math.sqrt(flag.length); i++) { 6             if (flag[i] == 0) 7                 for (int j = i; i * j < flag.length; j++) { 8                     flag[i * j] = 1; 9                 }10         }11         int count = 0;12         for (int i = 2; i < flag.length; i++)13             count += flag[i];14         BitSet bs = new BitSet();15         bs.ne16         return flag.length - count - 2;17     }

值得注意的是外迴圈只需要到根號n即可,因為內迴圈是從i*j即i平方開始的。在LeetCode如果沒加根號會產生溢出

 

Java 素數 prime numbers-LeetCode 204

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.