Home » Blog » Find Prime Number From 1 to n

# Find Prime Number From 1 to n

A Prime Number is a whole number greater than 1 whose only factors are 1 and itself. A factor is a whole numbers that can be divided evenly into another number. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors are called composite numbers.

Let’s take the last range for find prime numbers. We start one loop for get numbers from 1 to length entered by user, and one another loop inside this parent loop which is stared from 2. The child loop is used to divide the parent number with all the lesser number of parent number to know that when the parent number is dividable so that we can know that the number is prime or not. Inside the child loop we check that division of parent number and child number returns the mode 0 if yes then the number is not prime so the child loop is terminated and set flag to 1.

Now Parent loop check value of flag variable if it is 0 then the number is prime and it will print that parent number otherwise it will move to next number.

```import java.util.*;
public class prime
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int last,i=0,mod,j,flag=0,count=0;

System.out.println("***Prime Numbers***");
System.out.println("Enter Last Term = ");
last=sc.nextInt();
System.out.println("***Prime Numbers***");

while(i<=last)
{
flag=0;
j=2;
while(j<i)
{
if(i%j==0)
{
flag=1;
break;
}
j++;
}
if (flag==0)
{
System.out.println(i);
count++;
}
i++;
}
System.out.println("Total Prime Numbers in Range of "+last+" is "+count);
}
}```

Here is the OutPut

```***Prime Numbers***
Enter Last Term =
10
***Prime Numbers***
0
1
2
3
5
7
Total Prime Numbers in Range of 10 is 6```