DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: Problem with Prime Numbers

1. Registered User
Join Date
Jan 2005
Posts
1

## Problem with Prime Numbers

I need to write a program for class that can use a method to check whether or not a given number is prime, then print the first thousand prime numbers. However, my method's way of checking doesn't seem to be entirely accurate. I can't figure out a way to modify its code in order to be able to check if a number is prime, please help me correct it?

Here is what I've got so far:

public static boolean isPrime(int a)
{
return a % 2 != 0 || a == 2;
}

Where a is whatever number the user wishes to check. How can I modify this code in order to check if the number is prime more properly? I noticed that this code caught some of the primes but not all of them. For instance it considered 9 a prime since 9 is an odd number... but 9 isn't a prime, obviously. Thanks in advance!

2. Registered User
Join Date
Jan 2005
Location
Limerick, Ireland
Posts
19
Try this out I havent fully tested it but it should do the trick

public boolean isPrime(int num){
if (num == 2) return true;

// check for divisible by all even number
if (num % 2 == 0) return false;

// check for odd number only
for (int i = 3; i < num; i=i+2){
if (num % i == 0) return false;
}

return true; // all test pass..number is prime
}

3. Registered User
Join Date
Jan 2005
Posts
45
I suggest you check if a number is prime by

Given a number n, the possible divisors of n lie from n back to 1.

Since n is divisible by n and 1, use a for loop, start from n - 1 and ends at 1, then use a remainder to check whether n is divisible by n - 2, n - 3 etc. You should have a boolean variable called prime and set it to true initially. Every time n is divisble by a number, say n - 2, prime is set to false immediately and we quit the loop, of course , you should include prime in your for loop as well.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise