In this article, we will understand how to display all the prime numbers from 1 to N in Java. All possible positive numbers from 1 to infinity are called natural numbers. Prime numbers are special numbers who have only two factors 1 and itself and cannot be divided by any other number.
A number is a prime number if its only factors are 1 and itself. 11 is a prime number. Its factors are 1 and 11 itself. Some examples of prime numbers are 2, 3, 5, 7, 11, 13 and so on. 2 is the only even prime number. All other prime numbers are odd numbers.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the value of n :10
Output
The desired output would be −
2 3 5 7
Algorithm
Step1- Start Step 2- Declare an integer : n Step 3- Prompt the user to enter an integer value/ Hardcode the integer Step 4- Read the values Step 5- Using a while loop from 1 to n, check if the 'i' value is divisible by any number from 2 to i. Step 6- If yes, check the next number Step 7- If no, store the number as a prime number Step 8- Display the 'i' value as LCM of the two numbers Step 9- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool
.
import java.util.Scanner;
public class PrimeNumbers{
public static void main(String arg[]){
int i,n,counter, j;
Scanner scanner = new Scanner(System.in);
System.out.println("Required packages have been imported");
System.out.println("A reader object has been defined ");
System.out.print("Enter the n value : ");
n=scanner.nextInt();
System.out.print("Prime numbers between 1 to 10 are ");
for(j=2;j<=n;j++){
counter=0;
for(i=1;i<=j;i++){
if(j%i==0){
counter++;
}
}
if(counter==2)
System.out.print(j+" ");
}
}
}Output
Required packages have been imported A reader object has been defined Enter the n value : 10 Prime numbers between 1 to 10 are 2 3 5 7
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class PrimeNumbers{
public static void main(String arg[]){
int i,n,counter, j;
n= 10;
System.out.printf("Enter the n value is %d ", n);
System.out.printf("\nPrime numbers between 1 to %d are ", n);
for(j=2;j<=n;j++){
counter=0;
for(i=1;i<=j;i++){
if(j%i==0){
counter++;
}
}
if(counter==2)
System.out.print(j+" ");
}
}
}Output
Enter the n value is 10 Prime numbers between 1 to 10 are 2 3 5 7