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

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

提交回复
热议问题