Java Program to print all prime numbers till 20
Objective
Write a Java program to print all prime numbers up to 20.
Algorithm / Approach
- Start an outer
forloop withifrom 1 to 20. - Inside, initialize a counter variable
factorsto 0. - Start an inner
forloop withjfrom 1 toi. - Check if
iis divisible byj(i % j == 0). If yes, incrementfactors. - After the inner loop, check if
factors == 2. - 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)