Thinking in Java Fourth Edition Bruce Eckel Chapter 3 Exercise 4

Exercise 4: Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers (integral numbers that are not evenly divisible by any other numbers except for themselves and 1).

Solution:

public class Primes
{
    public static void main(String[] args)
    {
        for(int i = 1; i < 1000; i++ )
        {
            int factors = 0;
            for(int j = 1; j < (i + 2)/2; j++ )
            {
                if((i % j) == 0)
                {
                    factors++;
                }      
            }
            if(factors < 2)
            {
                System.out.println(i + " is prime");
            }
        }
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *