-
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!
-
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
}
-
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
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks