Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print all prime numbers till 20

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print all prime numbers till 20

Objective

Write a Java program to print all prime numbers up to 20.

Algorithm / Approach

  1. Start an outer for loop with i from 1 to 20.
  2. Inside, initialize a counter variable factors to 0.
  3. Start an inner for loop with j from 1 to i.
  4. Check if i is divisible by j (i % j == 0). If yes, increment factors.
  5. After the inner loop, check if factors == 2.
  6. If true, print the number i.
Test.java
class Test {
 public static void main(String[] a)
 {
  int factors;
  for(int i = 1; i<=20; i++) {
   factors = 0;
   for(int j = 1; j<=i; j++) {
    if(i%j ==0) 
     factors++;
   }
   if(factors ==2) {
    System.out.print(i+"  ");
   }
  } 
 }
}

Expected Output

2  3  5  7  11  13  17  19

Explanation of the Program

  • A prime number has exactly two distinct factors: 1 and itself.
  • The program checks every single number up to 20. For each number, it counts how many factors it has using the inner loop.
  • If the total factor count is exactly 2, it confirms the number is prime and prints it.
  • The number 1 only has one factor (itself), so factors == 1, and it is correctly excluded.

Complexity

Time Complexity O(n2) - Unoptimized brute force factor counting.
Space Complexity O(1)
ADVERTISEMENT