i want to print first 100 prime numbers. so, i created an array of int 100. I added first prime, bag[0] = 2, then for the following numbers, I tried to write an algorithm. It will start from 3 and goes on until array is full. Every number is decided to be if it is prime by whether it is divisible by the previous elements in array and if it is prime then it will be added to array.
here is my code:
public class Trial02
{
public static void main( String[] args)
{
int[] bag = new int[100];
bag[0] = 2; //first element of prime array
int valid = 1;
int i;
boolean result = true;
String str = "";
//starting from 3 it checks if a number is prime until array is full
for( i=3; valid<bag.length; i++)
{
//it checks if previous primes in array are divisible by current number until coming to current number
for(int k=0; k<valid; k++)
{
if( i % bag[k] == 0)
result = false;
}
if( result == true) //if it is prime it is added to array
{
bag[valid] = i;
valid ++;
}
}
//printing results
for(int m=0; m < bag.length; m++)
str = str + bag[m] + " ";
System.out.println("zaa xd");
System.out.println(str);
}
}
but it don’t give any output, just a blank. I couldn’t find where my mistake is.
Thanks in advance.
Your logic for determining the first 100 prime numbers is incorrect. And number of logical errors are present as indicated by others. I have re-written your code but not tested. I guess it will work: