How to find prime number from 1 to n?
In this program, we will learn to write a Java program that find prime numbers between 1 to n.
Algorithm to find prime numbers from 1 to n
- import java.io.*;
- create public class Prime{
- Create main function: public static void main(String[]args)throws IOException
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- Display message to enter a number to the user.
- Read-only integer numbers: int n=Integer.parseInt(br.readLine());
- for(int i=1;i<=n;i++)
- if((i==1)||(i==2))System.out.println(i);
- for(int j=2;j<i;j++)
- if(i%j==0){k=0;break;
- Else: k++;
- if(k>0)
- System.out.println(i);
Prime Numbers in Java Code
import java.io.*;
public class Prime {
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter n:");
int n=Integer.parseInt(br.readLine());
int k=0;
for(int i=1;i<=n;i++)
{
if((i==1)||(i==2))
System.out.println(i);
for(int j=2;j<i;j++)
{
if(i%j==0)
{
k=0;
break;
}
else
k++;
}
if(k>0)
System.out.println(i);
}
}
}
Expected Output:
5
1
2
3
5
Recommended Post:
- Python Odd and Even | if the condition
- Python Greater or equal number
- Python PALINDROME NUMBER
- Python FIBONACCI SERIES
- Python Dictionary | update() method
- Delete statement, Looping in the list In Python
- Odd and Even using Append in python
- Python | Simple Odd and Even number
Get Salesforce Answers
Tags: find prime numbers in java, prime number in java program, prime number in java code, nth prime number in java, prime number in java example, prime number in java using for loop