Prime numbers are the numbers
that is only divisible by 1 and itself.
Java Program to Print Prime Numbers
public class PrimeNumber
{
public static void main(String[] args)
{
int n = 15;
System.out.println("Prime Numbers :");
for (int i = 1; i <= n; i++)
{
int c = 0;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
c++;
break;
}
}
if (c == 0)
{
System.out.println(i);
}
}
}
}
Output:
Prime Numbers :
1
2
3
5
7
11
13
Java Program to Print Prime Numbers From 1 to n
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of n:");
int n = sc.nextInt();
System.out.println("Prime Numbers :");
for (int i = 1; i <= n; i++)
{
int c = 0;
for (int j = 2; j <= i / 2; j++)
{
if (i % j == 0)
{
c++;
break;
}
}
if (c == 0)
{
System.out.println(i);
}
}
}
}
Output:
Enter the value of n:20
Prime Numbers :
1
2
3
5
7
11
13
17
19
0 comments:
Post a Comment