Write a java program to print the first n prime number from the user:
A prime number (P) is a number greater than 1 whose only factors are 1 and the number (P) itself. Generally, we can determine a number is prime or not in below steps:
2 is only prime number which is also even number. So, if given number N is 2 the it is PRIME number.
If given number N is even number then it is NOT PRIME number.
Find out square root on N. Traverse all odd numbers up to the sqrt(N) and try to devide the N with current odd number. If remainder is 0 for any odd number then number is NOT PRIME.
Else – number is PRIME.
Program:
import java.util.Scanner;
class AshrafBin
{
public static void main(String args[])
{
int i,n,n1,count =0;
System.out.print("Enter the number :");
Scanner sc = new Scanner(System.in);
n1= sc.nextInt();
n=2;
while(count<n1)
{
for(i=2; i<n; i++)
{
if(n%i ==0)
{
break;
}
}
if(i==n)
{
System.out.println(i);
count++;
}
n++;
}
}
}
Output:
Write a java program to print a prime number to a given range :
import java.util.Scanner;
class PrimeNumbers
{
public static void main (String[] args)
{
int i =0,num =0,n;
String primeNumbers = "";
Scanner sc= new Scanner(System.in);
System.out.println("Enter the range to be print prime number");
n= sc.nextInt();
for (i = 1; i<= n; i++)
{
int counter=0;
for(num =i; num>=1; num--){
if(i%num==0)
counter = counter + 1;
}
if (counter ==2){
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to " + n +" are :");
System.out.println(primeNumbers);
}
}
Output:
READ MORE PAGES:
Tags
Java programming