Prime Number Generation in Java

This simple example demonstrates how to get the prime numbers using Java program for the given range. What is prime number?. A number which is divided only by 1 and itself is known as the prime number. If you take an example, 7 is a prime number, because it can be divided by only itself(7) or 1. However, 6 is not a prime number (it is a composite number) because it can be divided by 1,2,3 and 6.

Look at the below example:

package javabeat.net;

public class PrimeNumberExample {
	public static void main(String[] args) {
		int maxVal = 150;
		System.out.println("Generate Prime Numbers From 1 and " + maxVal);
		for (int i = 1; i < maxVal; i++) {
			boolean isPrimeNumberFlag = true;
			for (int j = 2; j < i; j++) {
				if (i % j == 0) {
					isPrimeNumberFlag = false;
					break; // exit the inner for loop
				}
			}
			if (isPrimeNumberFlag) {
				System.out.print(i + " ");
			}
		}
	}
}

Output

Generate Prime Numbers From 1 and 150
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149

In the above code, we create a two loops and divide the first loop by all the numbers in the second loop. If it is divided by any of the number in the second loop, then it is not a prime number.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*