1 2 Previous Next 19 Replies Latest reply: Nov 13, 2006 12:30 AM by 807599

i am writting a program for java were a user has to input a number and the output has to say if the number is a prime or not.. i can figure out how to do all the code the only thing i'm missing is the formula for prime numbers.. could anyone possibly help me out... thanks
• 1. Re: Java help please.. prime numbers
do you mean to say that you dont know how to test if a number is prime or not?!
yes
• 3. Re: Java help please.. prime numbers
A number is prime if it is only divisible by one and itself. So, If it is not divisible by another number between 1 and itself, then it is prime.
• 4. Re: Java help please.. prime numbers
This code should work:
``````bool isPrime(int numtotest)
{
for (int i = 2; i < numtotest; i++)
{
if (numtotest % i == 0)
{
return false;
}
}
return true;
}``````
Although I can't test it right now.
• 5. Re: Java help please.. prime numbers
``````if(the_number / 2 != %WholeNumber%);
{
System.out.println("Your number is prime... NO SOUP FOR YOU!!!");
}
else
{
}``````
I dont know what to fill in for %WholeNumber%. It would have to be some sorta hole number checker. Or u can do it backwards and do some sorta decimal checker. Not sure on how to make those checkers.
• 6. Re: Java help please.. prime numbers
lol, i took too long to type, answer for what goes in the if parentheses is up there.
• 7. Re: Java help please.. prime numbers
To make the code more efficient only loop until the square root of the number to test.
• 8. Re: Java help please.. prime numbers
is there even a way to put something as "whole numbers"
• 9. Re: Java help please.. prime numbers
What do you mean by "whole numbers"?

Use the code provided by JimmyM but end the loop when you reach the square root of the number rather than the number.
• 10. Re: Java help please.. prime numbers
sorry you lost me there... a little confused now
• 11. Re: Java help please.. prime numbers
sorry you lost me there... a little confused now
I wouldn't worry about it, use JimmyM's code. It will be slower for big numbers but it will work fine.
• 12. Re: Java help please.. prime numbers
If you don't understand and don't care just use the provided code as is.

If you do care, read on.

If the number is 24 it has a square root of approx 4.8 and the factors are:
1 * 24
2 * 12
3 * 8
4 * 6

All the factors on the left are less than 4.8 and all the factors on the right are > 4.8. So if you haven't found a factor for a given number before you hit the square root, you won't find a factor so you can stop looking. It makes your algorithm slightly more efficient.
• 13. Re: Java help please.. prime numbers
hmm i see... i'll see if i can understand this completely.. and by the way yes i do care!! heh
• 14. Re: Java help please.. prime numbers
so okay i'm trying to figure this out... if say i ask for 8 if it's a prime how would that work.. just trying to figure out the theory of your way..
1 2 Previous Next