• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

Prime Number Generation in Java

March 15, 2014 //  by Krishna Srinivasan

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.

Category: JavaTag: Core Java, Mathematics

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.

Previous Post: « Java Immutable Objects
Next Post: Java 8 Release and Features »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact