Print Prime Numbers in Java

In this post we will see couple of examples on how to print prime numbers in Java. A positive integer is called Prime Number when it is greater than 1 and divisible only with itself and by 1. Example: 2, 3, 5, 7, 11, 13, 17, 19 etc.,

Print Prime Numbers using custom square root function:

package com.techstackjournal;
/**
 * 
 * Program to print prime numbers within a given limit
 *
 */
public class PrimeNumbersMethod1 {
	public static void main(String args[]) {
		int limit = 200;
		for (int n = 2; n <= limit; n++) {
			if (isPrimeNumber(n)) {
				System.out.format("%d ",n);
			}
		}
	}
	/**
	 * Checks if given number is Prime or not
	 * 
	 * @param n
	 * @return
	 */
	private static boolean isPrimeNumber(int n) {
		for (int i = 2; i <= squareRoot(n); i++) {
			if (n % i == 0) {
				return false;
			}
		}
		return true;
	}
	/**
	 * Returns the square root of a number
	 * 
	 * @param num
	 * @return
	 */
	private static double squareRoot(double num) {
		double n2 = num / 2;
		double n1;
		do {
			n1 = n2;
			n2 = (n1 + num / n1) / 2;
		} while (n1 - n2 != 0);
		return n2;
	}
}

Prints Prime Numbers using Math class

package com.techstackjournal.java.basics;
/**
 * 
 * Program to print prime numbers within a given limit
 *
 */
public class PrimeNumbersMethod2 {
	public static void main(String args[]) {
		int limit = 200;
		for (int n = 2; n <= limit; n++) {
			if (isPrimeNumber(n)) {
				System.out.format("%d ", n);
			}
		}
	}
	/**
	 * Checks if given number is Prime or not
	 * 
	 * @param n
	 * @return
	 */
	private static boolean isPrimeNumber(int n) {
		for (int i = 2; i <= Math.sqrt(n); i++) {
			if (n % i == 0) {
				return false;
			}
		}
		return true;
	}
}

Leave a Comment