package cls;

public class main34 {
	public static void main(String[] args) {
		for(int i = 2; i <= 100; i++)
		{
			for(int j = 2; j <= i; j++)
			{
				if(i % j == 0)
				{
					break;
				}
				else
				{
					System.out.println(i + " ");
				}
			}
		}
	}

}

What am I doing wrong here ?

for(int j = 2; j <= i; j++) should be
for(int j = 2; j <i; j++)
or you will keep getting a number which is divisible by itself.

Also...
else {
System.out.println(i + " ");
}
will keep printing 'i' even though the number is NOT a prime number. You need to keep a flag checking if the number is or is not a prime number in the 2nd loop (j). Then if the flag indicates that it is still a prime number, you can display the message; otherwise, don't.

Edited 6 Years Ago by Taywin: n/a

package cls;

public class main34 {
	public static void main(String[] args) {
		for(int i = 2; i <= 100; i++)
		{
			for(int j = 2; j <= i; j++)
			{
				if(i % j == 0)
				{
					break;
				}
				else
				{
					System.out.println(i + " ");
				}
			}
		}
	}

}

What am I doing wrong here ?

I think that you are trying to use something that is similar to the Sieve of Eratosthenes I think you can improve your algorithm's complexity:

public static void findPrimeNumbers(int bound) 
{
   int sqUB = (int)Math.sqrt(bound); //We don't need to search further then the sqrt.
   boolean[] isNotPrime = new boolean[bound + 1];
   for (int i = 2; i <= sqUB; ++i) 
   {
     if(!isNotPrime[i]) //if we reached a number that has false, it must be a prime number
     {
        System.out.print(i + " ");
        for (int j = i * i; j <= bound; j += i)
        {
             isNotPrime[j] = true; // go over all the multiplications of this number, and mark them as not prime.
	}
     }
    }
    // The isNotPrime array now contains all the prime numbers, simply print them.
    for (int i = sqUB; i <= bound; i++)
    {
       if(!isNotPrime[i])
       {
          System.out.print(i + " ");
       }
    }
}
This article has been dead for over six months. Start a new discussion instead.