Prime Numbers in 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."); } }
Output:
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."); } }
Output:
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; } } }
Output:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

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 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.
