Table of Contents
Examples of Prime Numbers in Java
Example #1 – Using For-Loop
Example #2 – Using While Loop
Example #3 – Using Count
Conclusion
Home Java javaTutorial Prime Numbers in Java

Prime Numbers in Java

Aug 30, 2024 pm 04:27 PM
java

This post is about prime numbers in Java. A prime number is a kind of number which is divisible only by unity and the number itself. It is not divisible by any other number. Prime numbers are special kinds of numbers. The exception of numbers is 1 and 2. 1 is the only number that is neither prime nor composite. 2 is the only even number prime in nature. The opposite of prime numbers are numbers that are divisible by numbers other than the number itself as well as unity. Composite numbers and prime numbers are opposite to each other. Generally, prime numbers are odd numbers except for the number 2. It does not necessarily mean that an odd number is always a prime number because it might be divisible by 3 and any other odd number.

Examples of Prime Numbers in Java

Below are the examples of implementing prime numbers in java:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Example #1 – Using For-Loop

In the first coding example, we are going to check whether a number is prime or not. We first input the number using Buffered Reader Stream input. Then we have a for loop in which we are going to check the divisibility of the number by any other number except for 1 and any other number. The for loop starts from 2, and then the loop goes on till half the respective number. Then we have a variable that reports if the number is divisible or not by any number, which is a part of them loop. The code and the part of the loop are shown below, which inputs a number and gives the respective output whether that number is a prime number or not. In the program, the java.io.* is imported so that there are input/output operations appearing in the following code lines. Also, if there is an IOException, then it is treated differently. We have given the throws IO Exception command after the main’s declaration, which throws an exception that occurs during the input/output operation. Other than that, there are meaningful names used in the program for anyone reading the program to understand.

Code:

import java.io.*;
public class Prime
{
public static void main(String[] args) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER A NUMBER TO CHECK IF IT IS PRIME OR NOT");
int num= Integer.parseInt(br.readLine());
boolean count = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
count = true;
break;
}
}
if (!count)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Copy after login

Output:

Prime Numbers in Java

Prime Numbers in Java

Code Explanation: In the output, we see whether an inputted number is prime or not. First, we enter 29 as a number to check whether it is prime or not. We find out that 29 is a prime number as it is divisible by only the number of unity and the number itself. Except for that, it is not divisible by any other number.

Second, we enter another number to check whether the number is prime or not. We enter 58 as the number, and then we check whether the number is prime or not. Finally, we find out that 58 is not a prime number, but it is a composite number. It is an even number that is divisible by 2, 29 other than unity and the number itself.

Example #2 – Using While Loop

In the coding example, we are going to see the usage of the While loop for checking whether a number is prime or not. We use the same logic as the for loop, but we have a different outlook on the program.

Code:

import java.io.*;
public class PrimeNumber
{
public static void main(String[] args)throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER A NUMBER TO CHECK IF IT IS PRIME OR NOT");
int num= Integer.parseInt(br.readLine());
int i = 2;
boolean count = false;
while(i <= num/2)
{
// condition for nonprime number
if(num % i == 0)
{
count = true;
break;
}
++i;
}
if (!count)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Copy after login

Output:

Prime Numbers in Java

Prime Numbers in Java

Code Explanation: In the sample output, we input two odd numbers to check whether the numbers are prime or not. We enter 71 and 37 as two numbers and then finally find out that both the numbers are prime numbers as they are divisible by only 1 and the number itself.

Example #3 – Using Count

In this coding example, we are going to check the prime numbers within a range of numbers. We enter a minimum number as 20 and the maximum number as 50, and then we find the prime numbers within that range. It is a very easy program, and just by changing the min and max variables, we can find the prime numbers between the min and the max variables. The coding example is shown below.

Code:

import java.io.*;
public class PrimeRange
{
public static void main(String[] args)
{
int min = 20, max = 50;
while (min < max) {
boolean count = false;
for(int i = 2; i <= min/2; ++i) {
// condition for nonprime number
if(min % i == 0) {
count = true;
break;
}
}
if (!count)
System.out.print(min + " ");
++min;
}
}
}
Copy after login

Output:

Prime Numbers in Java

Code Explanation: In the above code, we find the number of prime numbers between 20 and 50. We find the numbers which are divisible only by unity and the number itself. The numbers which are prime are 23, 29, 31, 37, 41, 43, and 47. The code uses a single for loop, which is used to check the number’s divisibility by the respective for loop control variable. If the number is divisible, it is a composite number, and if the number is not divisible, it is a prime number.

Conclusion

In this article, we see the prime numbers working using a for loop and a while loop. Also, we see the prime numbers which are present within a certain range. The logic used for checking a prime number using a for loop and a while loop is almost the same. So, the checking of prime numbers is quite easy. The loop control variable is a very important factor in checking whether a number is prime or not.

The above is the detailed content of Prime Numbers in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles