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??
I’m solving this problem by,
- checking factors until num/2,
- push all into an array,
- check last element……
For prime I need to do more, but I’m stuck in initial stage.
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
dis a divisor, then so isnum/d.2. you needn’t check for any divisors greater than the
sqrt(num).To keep track of divisors, use a Set object.