DynamicTip:Use a for loop for the majority of applications since it is efficient and clear. Recursion is the greatest way to learn or demonstrate algorithmic reasoning, although loops are useful when you need additional control. Java Program to Print Prime Numbers from 1 to 100This program identifies and prints all prime numbers between 1 and 100 using a basic approach. This approach offers an easy but effective method to print prime numbers from 1 to 100 in Java. Algorithm to Print Prime Numbers from 1 to 100 in Java- Start
- Input or define the upper limit (e.g., 100)
- Repeat for each number num from 2 to the limit:
- Set a flag isPrime = true
- Repeat for each divisor from 2 to √num:
- If num is divisible by divisor, set isPrime = false and break
- If isPrime is still true, print num (it is a prime number)
- End
Code Example:public class PrimeNumbers {
public static void main(String[] args) {
int limit = 100;
System.out.println("Prime numbers between 1 and " + limit + " are:");
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}
Explanation:The program checks each number from 2 to 100 and determines whether it is prime. After making the initial assumption that a number is prime, it uses values ranging from 2 to the number's square root to test for divisibility. A number is designated as non-prime if it is divisible by any of these. Only prime numbers that have been verified are printed. Output:Prime numbers between 1 and 100 are:
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
Time and Space Complexity:Time Complexity: O(nn) (since each number is checked against divisors up to its square root). Space Complexity: O(1)(since no extra space is used apart from a few variables). Alternative Methods for Finding Prime NumbersThere are multiple ways to find prime numbers efficiently beyond the basic approach. To increase performance and versatility, the alternative approaches frequently make use of various data structures or optimizations. 1. Finding Prime Numbers Using an ArrayListPrime numbers are dynamically stored in an ArrayList before being printed using this approach. This method offers flexibility in subsequent processing and improves the handling of prime numbers. Code Example:import java.util.ArrayList;
public class PrimeNumbersList {
public static void main(String[] args) {
int limit = 100;
ArrayList<Integer> primes = new ArrayList<>();
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int divisor = 2; divisor * divisor <= num; divisor++) {
if (num % divisor == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.add(num);
}
}
System.out.println("Prime numbers between 1 and " + limit + ": " + primes);
}
}
Explanation:Using the square root approach, this program iterates over the integers 2 through 100 to determine whether each is prime. An ArrayList is used to hold numbers that are prime. The result is more organized and readable once every number has been verified since the entire list is printed at once. Output:Prime numbers between 1 and 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]
Time and Space Complexity:- Time Complexity: O(nn) (same as the previous method, as each number is checked up to its square root).
- Space Complexity: O(n) (since an ArrayList is used to store all prime numbers).
2. Sieve of Eratosthenes (Optimized Approach)A very effective way to find every prime number in a given range is to use the Sieve of Eratosthenes. It reduces needless calculations by consistently marking the multiples of each prime as non-prime rather than examining each integer separately. Using this approach, you can greatly speed up the process to print prime numbers from 1 to 100 in Java. Code Example:import java.util.Arrays;
public class SieveOfEratosthenes {
public static void main(String[] args) {
int limit = 100;
boolean[] isPrime = new boolean[limit + 1];
Arrays.fill(isPrime, true);
isPrime[0] = false; // 0 is not a prime
isPrime[1] = false; // 1 is not a prime
for (int p = 2; p * p <= limit; p++) {
if (isPrime[p]) {
for (int multiple = p * p; multiple <= limit; multiple += p) {
isPrime[multiple] = false;
}
}
}
System.out.println("Prime numbers between 1 and " + limit + ":");
for (int i = 2; i <= limit; i++) {
if (isPrime[i]) {
System.out.print(i + " ");
}
}
}
}
Explanation:This program sets up a boolean array in which each index indicates whether the corresponding number is prime. Starting from 2, it marks all multiples as non-prime. The process continues up to the square root of the limit. Any number still marked true is a prime and gets printed. Output:Prime numbers between 1 and 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
Time and Space Complexity:- Time Complexity: O(n log log n) (faster than previous methods).
- Space Complexity: O(n) (due to the boolean array storing prime statuses)
3. Using a Separate Method for Prime CheckThis method improves code structure by separating the prime-checking logic into a dedicated function. This makes the program more readable, reusable, and easier to maintain. Code Example:public class PrimeNumbersModular {
public static void main(String[] args) {
int maxLimit = 100;
System.out.println("Prime numbers between 1 and " + maxLimit + " are:");
for (int num = 2; num <= maxLimit; num++) {
if (checkPrime(num)) {
System.out.print(num + " ");
}
}
}
public static boolean checkPrime(int number) {
if (number < 2) {
return false;
}
for (int divisor = 2; divisor * divisor <= number; divisor++) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
}
Explanation:This program increases the clarity and modularity of the code by dividing the prime-checking logic into a separate checkPrime function. The main method iterates over the numbers from 2 to 100, calling checkPrime for each one. The checkPrime method checks if an integer is prime by dividing it up to its square root. A number returns true if its only divisors are 1 and itself. A number is printed if it is prime. This method facilitates debugging and increases code reuse. Output:Prime numbers between 1 and 100 are:
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
Time and Space Complexity:Time Complexity: O(nn) (since each number is checked against divisors up to its square root). Space Complexity: O(1) (only a few variables are used, with no additional data structures). 4. Using Java 8 Stream APIWith Java 8, the Stream API provides a functional and concise way to process collections of data. This approach allows us to filter and print prime numbers from 1 to 100 in Java efficiently using lambda expressions and streams. Code Example:import java.util.stream.IntStream;
public class PrimeNumbersStream {
public static void main(String[] args) {
int limit = 100;
System.out.println("Prime numbers between 1 and " + limit + " are:");
IntStream.rangeClosed(2, limit)
.filter(PrimeNumbersStream::isPrime)
.forEach(num -> System.out.print(num + " "));
}
public static boolean isPrime(int num) {
if (num < 2) {
return false;
}
return IntStream.rangeClosed(2, (int) Math.sqrt(num))
.allMatch(divisor -> num % divisor != 0);
}
}
Explanation:This code generates integers between 2 and 100 using IntStream, then utilizes the isPrime() function to filter out non-prime results. Using allMatch(), the isPrime() function determines whether a number has any divisors up to its square root, making sure that no integer in that range divides it entirely. Lastly, forEach() is used to output all prime integers. Output:Prime numbers between 1 and 100 are:
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
Time and Space Complexity:- Time Complexity: O(nn) (similar to the basic approach, but streamlined with Java 8 features).
- Space Complexity: O(1)(no extra storage except for function calls and stream operations).
Quick Recap- Use an ArrayList to store and display primes together.
- The Sieve of Eratosthenes efficiently marks non-primes for fast results.
- A separate method for checking primes makes the code cleaner and reusable.
- Java 8 Streams provide a modern, concise way to filter and print primes.
Choose the method that best fits your needs for performance, clarity, or code style. Prime Number Programs for Custom RangesReal-world applications frequently call for testing or listing primes within any user-specified range, even though printing prime numbers from 1 to 100 is a popular introductory exercise. Your Java application becomes more flexible and interactive when it is modified for custom ranges. How to Print Prime Numbers Within a User-Defined RangeTo print all prime numbers within a custom range, you need to: - Accept user input for the lower and upper bounds of the range.
- Iterate through the range using a loop.
- Check each number’s primality using a method such as trial division or an optimized algorithm.
- Store or print each prime found.
Typical Components: - User Input: Use Scanner to read the range from the user.
- For Loop: Iterate from the lower to the upper limit using the for loop.
- Primality Check: To find out if an integer is prime, use a helper method such as checkPrime(int number).
- ArrayList (Optional): Primes can be stored in an ArrayList (optional) for further processing or display.
Example: Java Program for Custom Rangeimport java.util.Scanner;
import java.util.ArrayList;
public class PrimesInRange {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get range from user
System.out.print("Enter the lower bound: ");
int lower = scanner.nextInt();
System.out.print("Enter the upper bound: ");
int upper = scanner.nextInt();
ArrayList<Integer> primes = new ArrayList<>();
// Find prime numbers in the given range
for (int num = lower; num <= upper; num++) {
if (checkPrime(num)) {
primes.add(num);
}
}
// Display result
System.out.println(
"Prime numbers between " + lower + " and " + upper + ": " + primes
);
scanner.close();
}
// Helper method to check primality
public static boolean checkPrime(int number) {
if (number < 2) {
return false;
}
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
How it works: - The user enters the desired numeric range.
- The program checks each number in that range for primality using the checkPrime method.
- All found primes are stored in an ArrayList and displayed at the end.
Practical Applications- Event-driven Java applications: Allow users to specify ranges dynamically.
- Reusable code: The same logic can be applied to check for primes in any range, not just 1–100.
- Optimized algorithms: For very large ranges, you can replace the basic primality check with more efficient algorithms (such as the Sieve of Eratosthenes for a range).
Tips for Custom Range Programs- Always validate user input to ensure the lower bound is less than or equal to the upper bound.
- Consider edge cases, such as negative numbers or ranges with no primes.
- Use more advanced methods or precompute primes for frequently asked questions or very big ranges.
Summary:In conclusion, your Java application will be more interactive and useful for real-world activities like filtering primes inside user-specified datasets or assisting with instructional tools if it is modified to accommodate custom ranges. Advanced Implementations and Optimizations for Prime Number GenerationWhen dealing with prime numbers in Java, one can use several advanced strategies to optimize the process beyond simple trial division, especially if the range is large or the application requires speed. Three of the best techniques that one can use are: Sieve of EratosthenesA well-known and incredibly effective method for locating all prime numbers up to a given limit is the Sieve of Eratosthenes. It designates the multiples of each prime as non-prime rather than examining each integer separately. This is particularly useful for producing a list of primes within a predetermined range and minimizes unnecessary tests. How it works: - Create a boolean array where each index represents a number’s primality.
- Mark 0 and 1 as non-prime.
- Starting from 2, for each number that is still marked as prime, mark all its multiples as non-prime.
- After processing, the indices still marked as true are primes.
Efficiency: - Time Complexity: O(n log log n)
- Space Complexity: O(n)
When to use: - Best for generating all primes up to a certain number, such as 1 to 100 or larger.
6k ± 1 MethodThe fact that all primes larger than three may be written in the form 6k ± 1 is the foundation of the 6k ± 1 optimization. This lowers the number of candidates you need to assess by allowing you to bypass numbers that are clearly composite (multiples of 2 and 3). How it works: - For numbers greater than 3, only test numbers where num % 6 == 1 or num % 6 == 5.
- For each candidate, check divisibility up to its square root, skipping even numbers and multiples of 3.
Efficiency: - Reduces the number of candidate numbers.
- When combined with the square root check, it balances speed and simplicity.
When to use: - Useful for mid-sized ranges where a full sieve may be unnecessary, but you want better performance than brute-force methods.
Wheel FactorizationWheel factorization extends the 6k ± 1 idea by using a larger cycle (the “wheel”) to skip even more composite numbers. For example, a 30-number wheel (based on the primes 2, 3, and 5) tests only numbers of the form 30k ± {1, 7, 11, 13, 17, 19, 23, 29}. How it works: - Use the product of the first few prime numbers to create a wheel (2 × 3 × 5 = 30).
- Test numbers are limited to those that match the wheel's pattern, excluding known composites.
- Combine each candidate with a primality check (such as the square root test).
Efficiency: - Lowers the number of checks even more than 6k ± 1.
- Good for applications that are performance-sensitive or have very wide ranges.
When to use: - Ideal for generating primes in large ranges or when integrating with sieve-based methods for even more efficiency.
Summary Table:
| Method |
Time Complexity |
Recommended Use Case |
| Sieve of Eratosthenes |
O(n log log n) |
Bulk prime generation |
| 6k ± 1 |
O(√n) per check |
Mid-sized, performance-focused |
| Wheel Factorization |
O(√n) per check |
Large ranges, maximum speed |
As the range increases, these sophisticated approaches enable you to create primes far more quickly than with simple ones. For most practical applications, the Sieve of Eratosthenes or 6k ± 1 method provides an excellent balance of speed and code clarity, while wheel factorization is best suited for very large-scale prime generation. ConclusionTo print prime numbers from 1 to 100 in Java is not just a simple code exercise; it's also a useful approach to learn how algorithms function in practical situations. Simple loops, effective checks, modular techniques, and the more sophisticated Sieve of Eratosthenes strategy are some of the methods that may be used to solve the problem. Each technique sharpens your problem-solving skills and gets you ready for challenging tasks in competitive programming, data structures, and cryptography. You gain confidence in your ability to write scalable, legible, and effective Java applications by becoming proficient in these strategies. Points to Remember- A prime number may only be divided by 1 and itself, and it is bigger than 1.
- For the divisibility check, always go up to the square root for better performance.
- The basic loop technique is suitable for small ranges and learning purposes.
- If you want to generate a large number of primes fast, the Sieve of Eratosthenes is the tool.
- Using modular and stream-based methods increases the code's readability and reusability.
Frequently Asked Questions1. Why are prime numbers important in hashing and cryptography?Since factoring large primes is computationally challenging, prime numbers form the basis of many cryptographic algorithms (such as RSA), which ensures the security of encrypted data. In hashing, using primes helps distribute hash values more uniformly, reducing collisions and improving lookup efficiency. 2. How do I choose the right prime-checking algorithm in Java for my needs?The simple trial division is adequate for short ranges or educational settings. To work with bigger numbers or generate a huge number of primes, employ optimal techniques such as 6k ± 1 or the Sieve of Eratosthenes. Use probabilistic techniques from Java's BigInteger class for really big integers (such as those used in encryption). 3. What are the main trade-offs between brute-force, sieve, and probabilistic methods?- Brute-force: Brute-force is easy to learn but sluggish for big inputs.
- Sieve of Eratosthenes: Fast for generating many primes, but uses more memory.
- Probabilistic (e.g., Miller-Rabin): Extremely fast for very large numbers, but there is a small chance of false positives.
4. When should I precompute primes in Java?Precompute primes when you need to perform many primality checks or factorization operations—this saves time in applications like competitive programming, cryptographic key generation, or data analysis. 5. How does Java’s BigInteger help with large prime numbers?BigInteger supports arbitrarily large integers and provides the isProbablePrime() method, which uses probabilistic algorithms to efficiently check if a large number is prime, essential for cryptographic applications. 6. How can edge cases affect prime number programs?Inputs that are not prime, such as 0 and 1, should always be handled. Use the right data types and techniques for very big numbers to prevent overflow or performance problems. 7. Can I reuse prime-checking logic in other programming languages?Indeed. Python, C++, and JavaScript all use the same basic logic (loops, conditionals, and optimizations). The only differences are in syntax and accessible libraries. 8. How do optimized algorithms improve real-world performance?Prime generation is sufficiently quick for use in encryption, massive data processing, and performance-critical systems thanks to optimized methods like the sieve or 6k ± 1 technique, which eliminate pointless checks. 9. In security applications, what are the dangers of employing ineffective prime-checking logic?Ineffective algorithms can cause system lag, create security holes, or facilitate brute-force assaults. For programming that is crucial to security, always employ tried-and-true, effective techniques. 10. How are primes used in generating RSA keys?RSA key generation involves selecting two large primes, multiplying them to form a modulus, and using their properties to create public and private keys. The security of RSA relies on the difficulty of factoring this modulus back into its original primes. Author:  Modepalli Rukmini  Rukmini Modepalli is an SEO Content Writer with 3+ years of experience creating high-quality educational content across Computer Science, technology, and career development domains. Passionate about making learning accessible and engaging, she specialises in transforming complex technical topics into easy-to-understand, value-driven content for students, job seekers, and professionals.
Her expertise spans SEO content strategy, technical writing, coding tutorials, interview preparation content, and educational resources designed to align with user intent and improve organic visibility. By combining research, storytelling, and SEO best practices, Rukmini creates content that educates, inspires, and helps learners achieve their academic and career goals.
|