Write a Java program that find prime numbers between 1 to n

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

  1. import java.io.*;
  2. create public class Prime{
  3. Create main function: public static void main(String[]args)throws IOException
  4. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  5. Display message to enter a number to the user.
  6. Read-only integer numbers: int n=Integer.parseInt(br.readLine());
  7. for(int i=1;i<=n;i++)
    1. if((i==1)||(i==2))
      System.out.println(i);
  8. for(int j=2;j<i;j++)
    1. if(i%j==0)
      {
      k=0;
      break;
  9. Else: k++;
  10. if(k>0)
    1. 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:

Enter n:
5
1
2
3
5
Algorithm to find prime numbers from 1 to n

Recommended Post:

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

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment