Reputation: 2028
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,
For prime I need to do more, but I'm stuck in initial stage.
Upvotes: 2
Views: 386
Reputation: 71979
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.
Upvotes: 3
Reputation: 42010
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.
Upvotes: 1
Reputation: 657
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].
Upvotes: 0
Reputation: 10541
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;
Upvotes: 0
Reputation: 1416
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.
Upvotes: 2