![]() |
Calculate prime numbers
Hope it hasn't been done before D:
But anyway, I did it all by myself. Took about two to three days of on and off thinking to figure out how to get it working. It seems to work correctly, comments and criticism of my probably horrible code are welcome. http://pi.monkeh.net/prime.cpp |
Try using 121 for your input ;)
|
121 doesn't work
Also, this code seems odd: :
while (n%2==0) // tests for even number. if it's even, it's not going to be prime.Edit: D'oh should have refreshed before I typed |
Ok, I looked through the code this time...
1) As The Dark mentioned, using a while when you always break is kinda silly. That's what if statements are for. 2) Don't call main() from your own program. 3) Your if statement is incorrect. It's also pretty redundant (you already know n%2 is 0, so n%4, n%6, n%8, n%10 is pointless) I took your code, sliced a lot out, and wrote my own version, if you'd like to compare. (I took out the system("pause") because it doesn't work on my computer :p) I didn't really comment it, but if you have questions, just ask :
|
Couple of comments on Jimbo's isPrime():
1. It assumes the input is an odd number. While it always true in this context when prime() calls it, a seperate call to isPrime(14) will return true instead of false because it is not checked for being a multiple of 2, and the loop will break before it reaches the other factor of 7. 2. In the n < 9 case, I think you meant to use "&&" instead of "||". And there needs to be a special case for when n is 2, because 2 is both even and prime. While the isPrime() works perfectly when called by the current prime() function because the input is never even or less than 9, it would yield incorrect results if called by another function that didn't filter anything out first. Here's an isPrime() that should work from any context: :
|
I found this on some random site and it made me laugh:
Quote:
|
Its funny you should bring this up. Earlier today I made a similar program, though mine just goes through all numbers upto 1,000,000,000:
:
I had an earlier version that brute forced every number, but I found that only using primes works much faster. |
._.
Guess I better hit the tutorial again. edit: Quote:
|
Quote:
|
I wrote this method for determining whether a number is prime a while ago. It is almost identical to the code posted by Kaja Fumei. I'm not sure if it completely correct though; if not I would appreciate any pointers.
:
|
| All times are GMT -5. The time now is 1:17 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC