Well, you probably don't want to get into the more esoteric algorithms for finding primes, but there are a few simple modifications that will reduce the number of checks you have to make.
If p%2==0 , it's prime.
If that is not the case, you can start the loop at 3 and increment by 2 for each iteration. You don't need to check any other even numbers.
Your loop also doesn't need to check any higher than sqrt(p) .
Maybe that helps a bit.
(I'm assuming you don't need to accomodate the check for p=1)
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
Wow that really makes sense. Thank you so much for the help. The only clarification that I need is that for
sqrt(p)
, where is that applied? Is it at the part where it says
for (int x = 2; x < p; x++)
?
Thanks
Yes, your prime check doesn't need to check numbers greater than the square root of the number. Any product greater than the number times itself will involve a factor less than the number itself, which you have already checked.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847
hussein87 you need to post your hw prob in its own thread...ALONG WITH YOUR CODE to get any kind of help.
jamesonh20
Junior Poster in Training
66 posts since Dec 2009
Reputation Points: 22
Solved Threads: 6
Yes, this thread is old and dead... but since someone pointed out to me a mistake in my post above, I'll address the mistake.
If p==2 , p is prime, for p!=2 if p%2==0 then it'snot prime.
Just wanted to clear that up.
Ezzaral
Posting Genius
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847