Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to test if a number is prime?

800965Jan 15 2011 — edited Jan 19 2011
Hi, I'm doing an exercise. I'm iterating through numbers from 2 to 100 (since 1 is not a prime number) and I need to test if the current number is a prime, if it is print it out. But I can't figure out the condition, how to test if a number is prime? So far I got this, but it prints all subsequent numbers, which is now obvious to me, but how to test for primes?
public class Main {
    public static void main(String[] args) {
        for (int i = 2; i <= 100; i++) {
            //Test if a number is a prime, if it is print it
            // The (i + 1) is because I want to divide i by any other number, so I thought i + 1
            if (((i % i) == 0) && ((i % 1) == 0) && ((i % (i + 1)) > 0)) {
                System.out.println(i);
            }  
        } 
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 16 2011
Added on Jan 15 2011
13 comments
351 views