# Check Prime numbers program

Printable View

• 03-11-2012, 08:41 PM
fallout87
Check Prime numbers program
Hi, I'm working on a program that checks if a user entered integer is prime or not.

It doesn't seem to work properly though. It thinks 25 is a prime number...and other ones that aren't or are prime is coming up wrong. Anyone have any ideas? Would be greatly appreciated.

Cheers
Fallout

public static void checkPrimeNumber()
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter an Integer value: ");
int n = sc.nextInt();

int hF = (int) Math.sqrt(number);
int prime = 0;

for (int i = 2; i < hF; i++)
{
if (n % i == 0)
{
prime = 0;
break;
}
else
{
prime = 1;
break;
}
}
if (prime == 1 || number == 2)
{
System.out.println(n + " is a prime number");
}
else
{
System.out.println(n + " is not a prime number");
}
programMenu();
}
• 03-11-2012, 09:10 PM
skynet357
Re: Check Prime numbers program
Two changes
------------------------
1. In the for loop use i<=hF.

2. Instead of assigning prime=0 or prime=1 use prime++ for (hF%i==0 to be true).

i mean

if(hF%i==0){
prime++;
}

no else part.

3. if prime>0 then not prime. Else prime.

I dint run these changes but I think this will work. :)