Let us see the java program to find the prime number. so first we should know about prime number. and logic to write a program, get to know about them below.
What is prime number?
Content.
- What is prime number.
- Logic for program.
- Program.
- Explanation.
- Output.
Prime number is the number which can divide by 1 and itself only.
Example:
2,3,5,7,11...
Logic for the Program.
- We need to give limits to start and end the prime number.
- Then make the number between the limits divide each other, if the reminder is a zero then it is prime number. if we get any number other then zero it is not a prime number it does of come in sequence.
- we use for loop and if statement.
Program
import java.io.*;
class prime
{
public static void main(String args[]) throws IOException
{
int n,m,i,j,c;
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(read);
System.out.println("Enter lower limit");
n=Integer.parseInt(in.readLine());
System.out.println("Enter upper limit");
m=Integer.parseInt(in.readLine());
System.out.println("Prime numbers between are :");
for(i=n;i<=m;i++)
{
c=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
c=c+1;
}
if(c==2)
System.out.println(i);
}
}
}
Explanation.
- We have given the class name has prime.
- public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
- String A,B, int x,y, char c is declaring the variable, s is declared to store 0.
- InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
- BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
- Now, we have to give condition which satisfies all the above in the logic for the program.
- I choose, for loop with i=n;i<=m;i++ as condition and it is nest with for loop with j=n;j<=m;j++.
- Then it as if statem to check for prime number.
- n is the lower limit we give, m is upper limit.
- System.out.println is used to display the given in output screen(make sure S in System is capital)
Know more about if statement.
Know more about for loop here.
Output:
Compile : javac prime.java
Run : java prim
Enter lower limit
0
Enter upper limit
20
Prime numbers between are :
2
3
5
7
11
13
17
19
Comments
Post a Comment