關於Java數組越界的一個詭異問題【leetcode204】

來源:互聯網
上載者:User

標籤:

刷leetcode204時,質數計算,在看完改進演算法後有個測試怎麼也過不了,資料越界報錯:

        Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2146737495

        仔細看都沒有找到原因,其中最後兩行輸出為:

              499813 499979  701  713
              -2146737495 499979  46349  46349

       很納悶,怎麼突然從701跳到了46349,而且i*j<n也是驗證過的,這個疑惑只在CSDN上找到這樣一個問答:

       請幫忙看一下這個程式為什麼會產生這樣的異常 [問題點數:20分]

       沒錯,因為代碼中沒有對i和j進行限制,所以它們會一直增長,知道超過int邊界,此時它們的乘積為負,負數當然是小於n,但是數組中肯定沒有這樣的地址!最後貼出問題代碼供參考:

public class Solution204 {    public int countPrimes(int n) {        boolean isPrime[] = new boolean[n];        for(int i = 0 ; i < n ; i++)            isPrime[i] = true;        int num = 0;        for(int i = 2 ; i < n ; i++){            if(!isPrime[i])                continue;            for(int j = i ; j*i < n ; j++) {                System.out.println(j * i + " " + n + "  " + i + "  " + j);                isPrime[j * i] = false;<span style="white-space:pre"></span>//當i和j很大時,它們的乘積仍然符合n,但是產生了越界異常            }        }        for(int i = 2 ; i < n ; i++)            if(isPrime[i] == true)                num++;        return num;    }    public static void main(String[] args) {        int n = new Solution204().countPrimes(499979);        System.out.println(n);    }}

另外,關於Sieve找質數演算法可以看看wiki:

        wiki:Sieve of Eratosthenes

關於Java數組越界的一個詭異問題【leetcode204】

聯繫我們

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