# How To Calculate Prime Numbers In Java

image credit:www.brooksdesign-ps.net |

So the logic we will follow is "check if the remainder for the number with the other number excluding 1,and the number should always have some value. else it is not a valid Prime number.

Let us get the number from user to test if that is a valid prime no

public static int getNumber() { int st=0; try{ st=Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter a valid Number here")); System.out.println(st); } catch(Exception e) { System.out.println(e); getNumber(); } return st; }

How the main method will be

public class PrimeNumber { /** * @param args */ public static void main(String[] args) { //----------------------------if you are going to check with a upper limit // TODO Auto-generated method stub int num=100; for(int i=2;i<num;i++ ) { calculatePrimi(i); } //One more way to get no from user... calculatePrimi(Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your Number here"))); calculatePrimi(getNumber()); }

The function will look like---

public static void calculatePrimi(int i) { //this will take some integer value boolean isPrime=false; //making it false initially for(int j=2;j<i;j++ ) { //our counter will run from 2 to number-1 if(i%j==0) { isPrime=false; break; } else{ isPrime=true; } } if (isPrime==true) { System.out.println("The number " +i " is a prime Number"); } else { System.out.println("The number " +i "is a Not prime Number"); } }

That's it you are done!!!

## Post a Comment