trying to generate prime numbers
so for my code i am trying to generate all the prime numbers between 2 and a given user input...i have succeeded in that. however, I also need to include all the excluded multiplies of that prime number.
EX:
2: 4 6 8 ....
3: 9 15 21....
this is what i have so far...
Code Java:
Scanner keyboard = new Scanner(System.in);
int size;
int [] numberArray;
int [] out;
System.out.println("Enter the size of the array from 1 to 100:");
size = keyboard.nextInt();
numberArray = new int[size];
//Fill the array.
for (int i=1; i<size; i++)
{
numberArray[i]=i;
}
numberArray[1] = -1;
//Identify 2 as the first prime number and then remove all numbers that are evenly divisible by 2
//start the for loop with 2
for (int i=2; i<size; i++){
//if the number has not already been discluded
if(numberArray[i] != -1){
for(int j = 0; j < size; j++ ){
// if the number is a multiple of another number
if(numberArray[j]%numberArray[i] == 0 && numberArray[j] != numberArray[i] ){
//disclude it
numberArray[j] = -1;
}
}
}
}
//print
for(int i = 1; i < size; i ++){
if(numberArray[i] != -1)
System.out.println(numberArray[i] + ":");
}
System.out.println();
any help would be greatly appreciated!
Re: trying to generate prime numbers
Re: trying to generate prime numbers
Welcome to the forums yingyang69.
If you scroll down to the bottom of this thread, there is a 'Similar Threads' box which will contain links that may help you.
http://www.javaprogrammingforums.com...-200-java.html
http://www.javaprogrammingforums.com...hile-loop.html
http://www.javaprogrammingforums.com...ci-series.html
I have compiled the code and there seems to be a few issues.
If you enter 1 as the size of the array, the program falls over with an ArrayIndexOutOfBoundsException exception.
I can not get it to display any prime numbers...
Re: trying to generate prime numbers
I have checked several of the similar threads and have so far found none that help me with my specific question...
Re: trying to generate prime numbers
First off, I think you need to get it to correctly take the size of the array, then the number from user input and print out the prime numbers.
When that is complete, we can work on showing the excluded multiplies.
Re: trying to generate prime numbers
I only need to start at 2 so I adjusted the instructions in the first println to state you must enter a number between 2 and 100. Thank you for catching that. When I enter a number greater than 2 the primes do show up.