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 ?

Recommended Answers

All 2 Replies

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.

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 + " ");
       }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.