views:

127

answers:

6
+2  A: 

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.

bkritzer
A: 

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;

tonio
since my variable num is double, i can't do int[num/2] ?
abhilashm86
@tonio num is a huge number. An int array of num/2 would be ~1.2 terabytes.
Jonathon
In this case, you should not use an array. And your program do not use the values in this array, except for the last one. Why not simply use an int value ?
tonio
A: 

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].

Daniel
+3  A: 

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.

Hank Gay
A: 

how long does this program execute people?? i'm curious just whether it'll complete or not, my dual core processor is fully being used!! i'll delete this program for sure and search a good algorithm to do, any good algorithms you know? what is range of long int in java? coz i'm unable to use num as int.....

abhilashm86
This is not a forum; new questions should be posted as new questions (or edited into the old question if they're simply refinements, but that is not the case here).
Michael Myers
+1  A: 

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.

GregS