The given Java Program guide you to Print all the Prime numbers up to a given number n. Let us see what exactly a prime number is.

What is a Prime Number ?

A number is said to be Prime, if it has only two factors i.e 1 and the number itself.
Example:
2 (the number 2 has only two factors i.e 1 and itself).
Similarly 3, 5, 7, 11, 71, etc.
Approach: We call the sub function given n number of times to perform the operation. This is a basic solution for beginners with O(n^2) time complexity. However, we can find the prime numbers more faster and better approach using Sieve of Eratosthenes with time complexity of O(n logn).

Java Code to Print all the Prime numbers in between 1 and n.

import java.util.Scanner;
public class Prime
{
    static boolean prime(int num)
    {
        int c = 0;
        for(int i=1; i<=num; i++)
        {
            if(num%i==0)
            {
                c++;
            }
        }
        if(c==2)
            return true;
        else
            return false;
    }
    public static void main(String[] args)
    {
        Scanner obj = new Scanner(System.in);
        System.out.println("enter the value for n");
        int n = obj.nextInt();
        for(int i=1; i<=20; i++)
        {
            if(prime(i))
                System.out.println(i);
        }
    }
}

Output:

enter the value for n
20
2
3
5
7
11
13
17
19