为什么在此素数检查中得到ArrayIndexOutOfBoundsException? [英] Why do I get an ArrayIndexOutOfBoundsException in this prime number check?
问题描述
我正在找出除num之外的最高素数,如程序所示, 数组和
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++;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at primenum.main(primenum.java:13)
//to find highest prime factor
public class primenum {
public static void main(String[] args) {
double num = 600851475143.0;
int j = 1;
int arr[] = {j};
for(int i=2; i<=num/2; i++)
{
if((num%i) == 0 )
{
arr[j] = i;
j++;
}
}
// take the last item from array, coz its last big prime
System.out.println("largest prime is "+ arr[j-1]);
}
}
解决此问题的最佳方法是什么?
What is best way to solve this problem??
我正在解决这个问题,
- 检查因子,直到num/2,
- 将所有内容推入数组
- 检查最后一个元素...
首要的是,我需要做更多的事情,但是我仍处于起步阶段.
For prime I need to do more, but I'm stuck in initial stage.
推荐答案
似乎您正在找到num
的所有除数;其中之一将是最大的主要因素.仅两个相关事实就可以使问题对于较小的数字变得易于处理:
1.如果d
是除数,则num/d
也是除数.
2.您不需要检查任何大于sqrt(num)
的除数.
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)
.
要跟踪除数,请使用Set对象.
To keep track of divisors, use a Set object.
这篇关于为什么在此素数检查中得到ArrayIndexOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!