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.

How the main method will be

```
public class PrimeNumber {
public static void main(String[] args) {
//if you are going to check with a upper limit
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");
}
}
```

Let us get the number from user to test if that is a valid prime no```
public static int getNumber()
{
int st=0;
try{
//take some number from user
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;
}
```

Optimization : The above logic works well for small range or if the number is small enough. if we deal with a very big prime number then the above code will keep evaluating from 2 to that big number. This put burden on processor. The below logic is applied on the prime number calculation to reduce the complexity and increase the efficiency.

Logic the for loop must not go till the number. It should go till the square root of that number. So for any number the possible divisor can be found between 2 to square root of that number.for square root we can use Math.sqrt(int a) function. This function returns double so we need to cast it to int.

Logic the for loop must not go till the number. It should go till the square root of that number. So for any number the possible divisor can be found between 2 to square root of that number.for square root we can use Math.sqrt(int a) function. This function returns double so we need to cast it to int.

```
public class CalculatePrime{
public static void main(String args[])
{
System.out.println(isPrime(1000));
}
public static boolean isPrime(int n) {
for (int i = 2; i <= (int)Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
```

The output of the code:$javac CalculatePrime.java

$java -Xmx128M -Xms16M CalculatePrime

false

How To Calculate Prime Numbers In Java
Reviewed by Animesh Chatterjee
on
March 24, 2013
Rating:

I could not :(( hope next time I will be able to (f)

ReplyDeleteNo Problem Ghanku...better luck next time

ReplyDelete