Posted on 25-04-2009
Filed Under (java, programming) by admin

Here’s a simple code that prints out the first 1000 Prime numbers, now keep in mind that Prime numbers start at 2, we exclude 0, and 1, because they are not prime numbers. A prime number is a positive integer that has exactly two factors, 1 and the number itself. We know 0 is neither a positive nor a negative number. Otherwise, 0 is a neutral number. So, it is not a prime number, and 1 is not a prime number, 1 has only one factor, that’s 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args){
    int num = 2;//2 is the first prime number
    int primeCounter = 0;
    boolean prime;
    while(primeCounter < 1000)
    {
       prime = true;
         for(int i = 2; i < num; i++)
        {
            if(num % i == 0)//checking for non prime numbers
            {
                prime = false;
                break;
            }
        }
        if(prime == true)
        {
            System.out.println(num+" is a prime number!");
            primeCounter++;//keeping count of primes numbers
        }
      num++;
    }
 }

Comments Off    Read More   

Comments are closed.