Why do I get an ArrayIndexOutOfBoundsException in this prime number check?

后端 未结 5 1382
孤独总比滥情好
孤独总比滥情好 2021-01-15 14:40

I was finding out highest prime factor which divides num, as shown in program, there\'s a issue with array and

arr[j] = i;
j++;
Excepti         


        
相关标签:
5条回答
  • 2021-01-15 15:14

    This line

    int arr[] = {j};
    

    Creates an array that only contains the value of j when it is executed. You probably want

    int arr[] = new int[j];
    

    UPDATE: Based on the answer you left below, trial division is taking too long. The Sieve of Eratosthenes is a classic algorithm that is pretty efficient, but the Sieve of Atkin is one of the most advanced algorithms for finding primes.

    0 讨论(0)
  • 2021-01-15 15:19

    By creating array arr[] = {j}, you have created an array which contains simply j, or 1. That means the length of the array is 1, because it contains 1 element. Thus, arr[1] is out of bounds. Java does not dynamically resize arrays, so you must create a sufficiently large array to contain all of the data you plan to hold. Either that or use something like an ArrayList, which is dynamically resizeable.

    0 讨论(0)
  • 2021-01-15 15:24

    Looks like you start j = 1 and your array only has one element in it to begin, so on the first pass through your for loop you look for arr[1], but the first element in an array is at arr[0]. Java arrays are zero indexed meaning if you have 10 elements in the array they are located in arr[0] to arr[9].

    0 讨论(0)
  • 2021-01-15 15:28

    Arrays in java are not lists: once allocated, your array won't grow magically.

    You created the array with: int arr[] = {j}; thus the array has one cell only.

    You should initialise your array with at least num/2 cells, with something like int arr[] = new int[num/2]; arr[0] = j;

    0 讨论(0)
  • 2021-01-15 15:29

    It looks like you are finding all divisors of num; one of these will be the largest prime factor. Two related facts alone should help make the problem tractable for smallish numbers:
    1. If d is a divisor, then so is num/d.
    2. you needn't check for any divisors greater than the sqrt(num).

    To keep track of divisors, use a Set object.

    0 讨论(0)
提交回复
热议问题