標籤:
刷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】