• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

5 Different Prime Number Program in Java | Prime Numbers between 1 to 100

September 4, 2019 by javainterviewpoint Leave a Comment

What is a Prime Number?

A Prime Number is a number which is greater than 1 and divisible by 1 and only itself. Some of the Prime Numbers are 2, 3, 5, 7, 11, 13, 17… In this Prime Number Program in Java, let’s take a look into the different prime number programs.

Is 0 a prime number?

0 is neither prime nor composite number, as per the definition, a prime number is a number with exactly two positive divisors, 1 and itself. Zero has an infinite number of divisors (we can divide 0 by all real numbers) Therefore, zero is not a Prime Number.

Is 1 a prime number?

1 is not considered as a Prime because it does not meet the criteria which is exactly two factors 1 and itself, whereas 1 has only one factor

Prime Number Program in Java using Scanner

We all know that the prime numbers can only be divided by itself and 1. Let’s understand the range to consider.

In general, a number cannot be divided by any number which is greater than itself and hence we can set the upper limit as to the number. Furthermore, we can limit the range by considering the fact that no number can have factors greater than the square root of the number (or) number by half (including the number itself).

For Example, Let’s take the number 19. It cannot be divided by any number greater than 19, 20 cannot divide 19 and range to consider is 19/2 which is 9.5 and hence we can consider the range between 2 to 9.

  • Get the number to check from the user.
  • Check whether the number is greater than 1, if the number is less than 1 then it cannot be a prime.
  • In an iterative loop, divide the number between the range 2 to number/2, and check if the remainder is not zero, if zero then the number is not a prime.
package com.javainterviewpoint;

import java.util.Scanner;

public class PrimeNumber1
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a number check :");
		int number = scanner.nextInt();
		
		if(checkPrime(number))
			System.out.println(number +" is a Prime Number");
		else
			System.out.println(number +" is not a Prime Number");
	}
	
	public static boolean checkPrime(int n)
	{
		if(n <= 1)
			return false;
		
		for(int i=2; i<= n/2; i++)
		{
			if((n % i) == 0)
				return false;
		}
		
		return true;
	}
}
  • Using Scanner get the input from the user and store it in the variable “number”.
  • The checkPrime() method, checks whether the number passed is prime or not. It returns boolean values based on the below criteria
    • Returns false when the number is less than or equal to 1.
    • Returns false when the remainder is zero.
    • If the number is greater than 1 and it is not divisible any number within the range of 2 to number/2 then it returns true.

Prime Number Program in Java using While Loop

We can also use the while loop instead of for loop, let’s re-write the above code using while loop.

We just need to make some minor modifications like the initialization of “i” [i=2] happens just before the start of the loop, incrementation of “i” [i++] happens inside the loop and of course, we need to change for loop into while loop.

package com.javainterviewpoint;

import java.util.Scanner;

public class PrimeNumber2
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a number check :");
		int number = scanner.nextInt();
		
		if(checkPrime(number))
			System.out.println(number +" is a Prime Number");
		else
			System.out.println(number +" is not a Prime Number");
	}
	
	public static boolean checkPrime(int n)
	{
		if(n <= 1)
			return false;
		
		int i=2;
		while(i<= n/2)
		{
			if((n % i) == 0)
				return false;
			i++;
		}
		
		return true;
	}
}

Java program to find all Prime Numbers from array

In this approach, let’s get the input from the user and store it in the array and find all the prime numbers from array.

  • Get the size of the array from the user and create an array to store the input numbers
  • Get the elements of the array from the user and store it in the array which is created in the previous step
  • Finally, iterate the array and pass each element to the checkPrime() method and perform the prime validation
package com.javainterviewpoint;

import java.util.Arrays;
import java.util.Scanner;

public class PrimeNumber3
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the size of the array :");
		int arraySize = scanner.nextInt();

		int[] values = new int[arraySize];

		System.out.println("Enter the elements of the array : ");
		for (int i = 0; i < arraySize; i++)
		{
			values[i] = scanner.nextInt();
		}

		System.out.println("*** Printing the Prime Numbers ***");
		for (int i = 0; i < arraySize; i++)
		{
			if (checkPrime(values[i]))
			{
				System.out.println(values[i]);
			}
		}

	}

	public static boolean checkPrime(int n)
	{
		if (n <= 1)
			return false;

		int i = 2;
		while (i <= n / 2)
		{
			if ((n % i) == 0)
				return false;
			i++;
		}

		return true;
	}
}

Output:

Enter the size of the array :
5
Enter the elements of the array : 
1 2 3 4 5
*** Printing the Prime Numbers ***
2
3
5

Prime Numbers between 1 to 100 / List of Prime Numbers from 1 to 100

Let’s print all the prime numbers between 1 to 100

package com.javainterviewpoint;

public class PrimeNumber4
{
	public static void main(String[] args)
	{
		System.out.println("*** Prime Numbers between 1 to 100 ***");
		for (int i = 2; i < 100; i++)
		{
			if (checkPrime(i))
			{
				System.out.print(i+"  ");
			}
		}
	}
	
	public static boolean checkPrime(int n)
	{
		if(n <= 1)
			return false;
		
		int i=2;
		while(i <= n/2)
		{
			if((n % i) == 0)
				return false;
			i++;
		}
		
		return true;
	}
}

Output:

*** Prime Numbers between 1 to 100 ***
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

Find all Prime Numbers between 1 to N

  • Get the upper limit from the user and store it in the variable “N”
  • Start the loop from 2 to N, for each iteration increment the loop by 1
  • In the checkPrime() method, we have used a boolean flag. It will be set to false when the number is less than 1 or if the number is divisible by number/2.
  • Validate the boolean returned by the checkPrime() and print the number if the boolean returned is true.
package com.javainterviewpoint;

import java.util.Scanner;

public class PrimeNumber5
{
	public static void main(String[] args)
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the Upper limit :");
		int N = scanner.nextInt();
		
		System.out.println("*** Prime Numbers between 1 to N ***");
		for (int i = 2; i <= N; i++)
		{
			if (checkPrime(i))
			{
				System.out.print(i+"  ");
			}
		}
	}
	
	public static boolean checkPrime(int n)
	{
		boolean flag = true;
		
		if(n <= 1)
			flag = false;
		
		for(int i=2; i<= n/2; i++)
		{
			if((n % i) == 0)
                        {
				flag = false;
                                break; 
                         }
		}
		
		return flag;
	}
}

Output:

Enter the Upper limit :
55
*** Prime Numbers between 1 to N ***
2  3  5  7  11  13  17  19  23  29  31  37  41  43  47  53

Bonus – Prime Numbers Chart

Below table contains the list of Prime Numbers from 1 to 100. All the prime numbers are shaded with a green background.

Prime Numbers Chart

Happy Learning!!

Filed Under: Core Java, Java, Java Interview Tagged With: 1 to 100, 1 to N, find all Prime Numbers, Prime Number, Prime Number Program, Prime Numbers Chart

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·