Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Prime Numbers in Range in Java

Find primes from 1 to 100 in Java with an isPrime helper that tests odd divisors through the square root. Two is included, while one is not prime.

IntermediateJava Loop ProgramsExample 9 of 25
prime-numbers-in-range.java
1public class Main {
2 private static boolean isPrime(int n) {
3 if (n <= 1) return false;
4 if (n == 2) return true;
5 if (n % 2 == 0) return false;
6 for (int i = 3; i * i <= n; i += 2) {
7 if (n % i == 0) return false;
8 }
9 return true;
10 }
11
12 public static void main(String[] args) {
13 for (int i = 1; i <= 100; i++) {
14 if (isPrime(i)) {
15 System.out.print(i + " ");
16 }
17 }
18 }
19}

Sample Output

2 3 5 7 11 13 ... 97

The full list contains 25 primes, beginning with 2 and ending with 97. Non-prime candidates produce no output.

In this one

  • Define a prime number
  • Reuse a prime test across a range
  • Stop divisor checks at the square root

How it works

  1. 1

    Visit each candidate from 1 to 100.

  2. 2

    Reject 1 and handle 2 separately.

  3. 3

    Try odd divisors through the square-root limit.

  4. 4

    Print candidates with no divisor found.

Edge cases

First candidate

Test 1

The helper returns false because primes must be greater than one.

Odd square

Test 49

The loop includes divisor 7 and rejects 49.

What's going on

List the prime numbers from 1 through 100. A prime is a whole number greater than one with exactly two positive divisors: one and itself. This exercise shows how one reusable test can filter a complete range of values.

The helper isPrime rejects values at most one, accepts two, and rejects other even numbers. It then tries odd divisors from three while i * i <= n. A divisor is a number that divides another exactly. The % operator supplies the remainder after division, so a zero result means a divisor has been found.

The outer loop prints a number only when isPrime returns true. Testing through the square root is enough because factors occur in pairs: a larger factor has a smaller partner. The range here is small, so i * i stays safe. Do not include one in the prime list, and do not stop before testing an exact square root.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the smallest prime?

Pick an answer to check it.

Question 2

Does 49 pass isPrime?

Pick an answer to check it.

Questions people ask

Why are even divisors skipped after two?

Any other even candidate has already been rejected, so only odd factors can remain.

Why include i * i == n?

Perfect squares such as 49 have a divisor exactly at the square root.

Does the program print dots in the middle?

No. The output below contains every prime in the range.