prime number question

Started by
15 comments, last by omegasyphon 22 years, 5 months ago
Fast prime number checker.

BeerNutts, your function's logic is the wrong way round: it'll return TRUE if a number is not prime, and FALSE otherwise.

      bool sieve[65536];long primes[65536], primeCount = 0;void initSieve (){  for (int i = 2; i < 65536; ++i)    if (!sieve[i])      for (int j = i * 2; j < 65536; j += i)        sieve[i] = true;  for (int i = 2; i < 65536; ++i)    if (!sieve[i])      primes[primeCount++] = i;}bool isPrime (long n){  // If n fits in the sieve, then it's a simple lookup.  if (n < 65536)    return !sieve[n];  // Elsewise, test it against each prime that is less than sqrt(n)  for (int i = 0; (i < primeCount) && (primes[i] < sqrt(n)); ++i)    if (0 == n % primes[i])      return false;  return true;}      


Signatures? We don't need no steenking signatures!

Edit: Failed to use the English language.
Edit: Removed a rogue 7.

Edited by - Mayrel on November 1, 2001 2:27:02 PM
CoV
Advertisement
There goes the homework assignment...
thanks, i got it working.
Aww, TRUE, FALSE, what's the big difference? Just change those two and it works

Oh, and Oluseyi, you're way goes against my coding standards: Only 1 return per function (I know, I'm strict).


Edited by - BeerNutts on November 1, 2001 4:35:04 PM

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

Heh you can tell it''s toward the beginnig of the school year, all these questions cropping up about finding primes, taking the negative of a number without using the - sign, etc .

Anthracks
quote:Original post by BeerNutts
Oh, and Oluseyi, you''re way goes against my coding standards: Only 1 return per function (I know, I''m strict).

Interesting paradigm; I use returns to exit early. Besides, some functions do have multiple return values and decaring an extra variable just to hold them isn''t always elegant (boolean functions - as above - come to mind). In any case, to each his own.
quote:Original post by BeerNutts
Aww, TRUE, FALSE, what's the big difference? Just change those two and it works

In this case, the difference between the A and D grades.
quote:
Oh, and Oluseyi, you're way goes against my coding standards: Only 1 return per function (I know, I'm strict).

You sound like a vulcan, but I don't see no points on your ears, boy.

Seriously, you a Pascal programmar in a previous life?

Signatures? We don't need no steenking signatures!

Edited by - Mayrel on November 2, 2001 9:02:24 AM
CoV

This topic is closed to new replies.

Advertisement