TechArena Community program to check prime number in java

#1
24-11-2009
 Member Join Date: May 2009 Posts: 856
program to check prime number in java

Hi,
I get this program "to check entered number is prime number or not" in my exam.I tried various method but I am not able to write this program.So I am just asking solution of this program on this forum.If any one have solution of this program please give it to me.

Last edited by Bansi_WADIA : 24-11-2009 at 10:40 PM.
#2
24-11-2009
 Member Join Date: Apr 2008 Posts: 2,001
Re: program to check prime number in java

I write this program just using if statement.Try to compile this program in your computer.

Code:
``` class PrimeNumber
{
public static void main(String[] args)
{
int Num1 = 11;
int p;
for (p=2; pi < Num ;p++ )
{
int x = num%p;
if (x==0)
{
System.out.println("Entered number is not Prime!");
break;
}
}
if(p == Num)
{
System.out.println("Prime number!");
}
}
}```
#3
24-11-2009
 Member Join Date: May 2008 Posts: 2,293
Re: program to check prime number in java

Try following code to check prime number.

Code:
```           class PrimeNumber
{

public static void main(String args[])
{

int Num = Integer.parseInt(args[0]);

int opt=0;

for(int p=2;p<num;p++)
{

if(num%p==0)

{

System.out.println(Num+" is not a Prime Number");

opt = 1;

break;

}

}

if(opt==0)

System.out.println(Num+" is a Prime Number");

}

}```
#4
24-11-2009
 Member Join Date: Oct 2005 Posts: 2,389
Re: program to check prime number in java

I just write program which is small but very complex.Try to understand each step.

Code:
```        public static boolean prime (long PrimeNmber)
{
for (int x=1; x<PrimeNmber; x+=2)
{
if ((PrimeNmber%x==0 && x!=1) || (PrimeNmber%2==0 && PrimeNmber!=2))
{
return false;
}
}
return true;
}```

Last edited by Reegan : 24-11-2009 at 11:05 PM.

 Tags: