This Java program demonstrates how to calculate and print prime numbers. Whether you aim to print prime numbers from 1 to 100 in Java or want to understand the logic behind identifying a prime number in Java, this tutorial has you covered.
What is a Prime Number?
Prime numbers are unique natural numbers greater than 1, divisible only by 1 and themselves. Unlike composite numbers, they can't be divided by smaller natural numbers. Prime numbers are significant in fields like number theory, cryptography, and computer science.
Examples of prime numbers:
A few prime numbers are 2, 3, 5, 7, 11, and 13. These numbers can only be divided evenly by 1 or themselves, so they are prime numbers.
Prime Number Check Program in Java
Program:
public class PrimeNumbers {
public static void main(String[] args) {
int num = 20; // Define the upper limit
int count; // Initialize counter for divisibility checks
// Iterate from 1 up to 'num' to identify prime numbers
for (int i = 1; i <= num; i++) {
count = 0; // Reset counter for each 'i'
// Check for divisibility from 2 up to i/2
for (int j = 2; j <= i / 2; j++) {
if (i % j == 0) {
count++; // Increment if 'i' is divisible by 'j'
break; // Exit loop if a divisor is found
}
}
// If the count is 0, 'i' is prime
if (count == 0) {
System.out.println(i); // Output the prime number
}
}
}
}
Program Output:
Execute this Java program to generate prime numbers. You will get the list of prime numbers up to 20 as follows:
1
2
3
5
7
11
13
17
19
Code Explanation:
Here is a line-by-line explanation of the prime no program in Java:
- Class and Main Method: First, create a class named
PrimeNumbers
. Inside this class, declare themain()
method. - Variable Initialization: Declare two integer variables
num
andcount
. Setnum
to 20, which is the upper limit for the prime number search. - Outer Loop: An outer loop runs from 1 to
num
. Initializecount
to zero at the start of each iteration. - Inner Loop: An inner loop runs from 2 to
i / 2
and checks ifi
is divisible by any number in this range. If a divisor is found,count
increments by one, and the loop exits. - Prime Identification: After the inner loop, if
count
remains zero, the program considersi
as a prime number and prints it.
Conclusion
This Java tutorial provides an efficient and straightforward way to calculate prime numbers up to a given limit. Whether you aim to print a list of prime numbers in Java or understand the core logic behind identifying them, this guide makes it accessible to everyone.