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

后端 未结 5 1384
孤独总比滥情好
孤独总比滥情好 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.

提交回复
热议问题