Java Program to Print Prime Numbers from 1 to 100

โšก Smart Summary

Program to Print Prime Number From 1 to 100 in Java scans every value in a range and reports those with exactly two divisors. This article explains the definition, the checking method, the complete program, the Sieve of Eratosthenes, and a performance comparison with verified output.

  • ๐Ÿ”ข Definition Rule: A prime number is greater than 1 and divisible only by 1 and itself, which excludes 0 and 1 entirely.
  • ๐Ÿ” Range Scan: An outer loop walks from 2 to the upper limit and delegates each value to a reusable checking method.
  • โœ… Boolean Method: CheckPrime returns false on the first divisor found and true when the loop completes without a match.
  • โˆš Divisor Bound: Testing up to half the value is correct, and stopping at the square root produces the same answer far faster.
  • ๐Ÿงฎ Result Set: Exactly 25 prime numbers exist between 1 and 100, ending with 97.
  • โšก Sieve Method: The Sieve of Eratosthenes marks multiples in a boolean array and runs in O(n log log n) time.
  • ๐Ÿงช Verification Practice: Confirm that 2 is included and that 1 is excluded before trusting any implementation.

Prime Numbers 1 to 100 in Java

What is a Prime Number?

A Prime Number is a number that is only divisible by one or itself. It is a natural number greater than one that is not a product of two smaller natural numbers. For example, 11 is only divisible by one or itself. Other prime numbers are 2, 3, 5, 7, 11, 13, 17, and so on.

Note: 0 and 1 are not prime numbers. 2 is the only even prime number.

Between 1 and 100 there are exactly 25 prime numbers. The grid below groups them by decade, which makes the thinning pattern visible as the values grow.

Range Prime Numbers Count
1 – 20 2, 3, 5, 7, 11, 13, 17, 19 8
21 – 40 23, 29, 31, 37 4
41 – 60 41, 43, 47, 53, 59 5
61 – 80 61, 67, 71, 73, 79 5
81 – 100 83, 89, 97 3

How to Print Prime Numbers Between 1 to 100 Program in Java

Below is the Java program to print prime numbers from 1 to 100:

Program Logic:

  • The main method of the prime number program in Java contains a loop to check prime numbers between 1 to 100 one by one.
  • The main method calls the method CheckPrime to determine whether a number is a prime number in Java or not.
  • We need to divide an input number, say 17, from values 2 to 17 and check the remainder. If the remainder is 0, the number is not prime.
  • No number is divisible by more than half of itself. So, we need to loop through just numberToCheck/2. If the input is 17, half is 8.5, and the loop will iterate through values 2 to 8.
  • If numberToCheck is entirely divisible by another number, we return false, and the loop is broken.
  • If numberToCheck is prime, we return true.
  • In the main method for prime numbers 1 to 100 in Java, check whether isPrime is TRUE and add the value to the primeNumbersFound String.
  • Lastly, print prime numbers from 1 to 100 in Java.

Separating the check into its own method is what makes the program reusable. The same CheckPrime method can be called with any upper limit simply by changing the maxCheck variable.

public class PrimeNumbers {

    public static void main(String[] args) {

        int i;
        int num = 0;
        int maxCheck = 100; // maxCheck limit till which you want to find prime numbers
        boolean isPrime = true;

        //Empty String
        String primeNumbersFound = "";

        //Start loop 2 to maxCheck
        for (i = 2; i <= maxCheck; i++) {
            isPrime = CheckPrime(i);
            if (isPrime) {
                primeNumbersFound = primeNumbersFound + i + " ";
            }
        }
        System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
        // Print prime numbers from 1 to maxCheck
        System.out.println(primeNumbersFound);
    }
    public static boolean CheckPrime(int numberToCheck) {
        int remainder;
        for (int i = 2; i <= numberToCheck / 2; i++) {
            remainder = numberToCheck % i;
            //if remainder is 0 then the number is not prime and we break the loop. Else continue the loop
            if (remainder == 0) {
                return false;
            }
        }
        return true;

    }

}

Expected Output:

The output of the prime number between 1 to 100 in the Java program will be:

Prime numbers from 1 to 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

The value 2 passes because the inner loop condition i <= 2 / 2 evaluates to 2 <= 1, which is false straight away, so the method returns true without a single division.

Optimized Version Using the Square Root Bound

Dividing up to half of the number is correct but performs unnecessary work. Divisors always occur in pairs around the square root, so any factor above โˆšn has a partner below it that was already tested.

public class PrimeNumbersOptimized {

    public static void main(String[] args) {
        int maxCheck = 100;
        int count = 0;
        StringBuilder result = new StringBuilder();

        for (int i = 2; i <= maxCheck; i++) {
            if (isPrime(i)) {
                result.append(i).append(" ");
                count++;
            }
        }

        System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
        System.out.println(result.toString().trim());
        System.out.println("Total primes found: " + count);
    }

    public static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n == 2) return true;
        if (n % 2 == 0) return false;

        // test only odd divisors up to the square root
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) return false;
        }
        return true;
    }
}

Output:

Prime numbers from 1 to 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
Total primes found: 25

๐Ÿ’ก Tip: StringBuilder replaces repeated String concatenation inside the loop. Each += on a String creates a new object, which becomes measurable once the upper limit reaches several thousand.

Print Prime Numbers Using the Sieve of Eratosthenes

When every prime in a range is needed, trial division is the wrong tool. The Sieve of Eratosthenes builds a boolean array, marks the multiples of each prime as composite, and reads off whatever remains unmarked.

The method works in three steps:

  1. Create a boolean array of size n+1 and assume every index from 2 upwards is prime.
  2. Starting at 2, mark every multiple of the current prime as composite.
  3. Advance to the next unmarked index and repeat until the square root of n is passed.
import java.util.Arrays;

public class SieveOfEratosthenes {

    public static void main(String[] args) {
        int n = 100;
        boolean[] composite = new boolean[n + 1];

        for (int p = 2; p * p <= n; p++) {
            if (!composite[p]) {
                // start at p*p because smaller multiples are already marked
                for (int multiple = p * p; multiple <= n; multiple += p) {
                    composite[multiple] = true;
                }
            }
        }

        StringBuilder result = new StringBuilder();
        for (int i = 2; i <= n; i++) {
            if (!composite[i]) {
                result.append(i).append(" ");
            }
        }

        System.out.println("Prime numbers from 1 to " + n + " are:");
        System.out.println(result.toString().trim());
    }
}

Output:

Prime numbers from 1 to 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

Comparison of the Three Approaches

All three programs print the same 25 values, so the choice depends entirely on the size of the range.

Approach Time Complexity Extra Memory Best Range
Trial division to n/2 O(nยฒ) O(1) Up to a few thousand
Trial division to โˆšn O(nโˆšn) O(1) Up to a few hundred thousand
Sieve of Eratosthenes O(n log log n) O(n) Millions of values

Check our program to find prime numbers from any input number when a single value rather than a range must be tested. For further loop driven exercises, review the Fibonacci series in Java, the Java palindrome program, and the Bubble Sort algorithm in Java. The boolean array used by the sieve is explained further in Java arrays.

FAQs

There are exactly 25. The sequence begins at 2 and ends at 97, and the density decreases steadily as the values grow larger.

The inner loop condition becomes 2 <= 1, which is false immediately, so no division runs and the method returns true. That single case is worth testing in every implementation.

Change the maxCheck variable to 500. To start above 1, adjust the initial value of the outer loop counter instead, and leave the checking method untouched.

Every smaller multiple of p already contains a smaller prime factor and was marked during an earlier pass. Starting at p squared avoids repeating that work.

They typically return trial division unless the prompt mentions a large range or performance. Stating the upper limit in the request usually produces the sieve instead.

Primes are chosen as hash table and feature bucket sizes because they distribute keys evenly and reduce collisions. They also seed hashing functions used in feature vectorisation.

Summarize this post with: