00001 // Filename: primeNumberGenerator.cxx 00002 // Created by: drose (22Mar01) 00003 // 00004 //////////////////////////////////////////////////////////////////// 00005 // 00006 // PANDA 3D SOFTWARE 00007 // Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved 00008 // 00009 // All use of this software is subject to the terms of the Panda 3d 00010 // Software license. You should have received a copy of this license 00011 // along with this source code; you will also find a current copy of 00012 // the license at http://www.panda3d.org/license.txt . 00013 // 00014 // To contact the maintainers of this program write to 00015 // panda3d@yahoogroups.com . 00016 // 00017 //////////////////////////////////////////////////////////////////// 00018 00019 #include "primeNumberGenerator.h" 00020 00021 00022 //////////////////////////////////////////////////////////////////// 00023 // Function: PrimeNumberGenerator::Constructor 00024 // Access: Public 00025 // Description: 00026 //////////////////////////////////////////////////////////////////// 00027 PrimeNumberGenerator:: 00028 PrimeNumberGenerator() { 00029 _primes.push_back(2); 00030 } 00031 00032 //////////////////////////////////////////////////////////////////// 00033 // Function: PrimeNumberGenerator::Indexing operator 00034 // Access: Public 00035 // Description: Returns the nth prime number. this[0] returns 2, 00036 // this[1] returns 3; successively larger values of n 00037 // return larger prime numbers, up to the largest prime 00038 // number that can be represented in an int. 00039 //////////////////////////////////////////////////////////////////// 00040 int PrimeNumberGenerator:: 00041 operator [] (int n) { 00042 nassertr(n >= 0, 0); 00043 00044 // Compute the prime numbers between the last-computed prime number 00045 // and n. 00046 int candidate = _primes.back() + 1; 00047 while ((int)_primes.size() <= n) { 00048 // Is candidate prime? It is not if any one of the already-found 00049 // prime numbers (up to its square root) divides it evenly. 00050 bool maybe_prime = true; 00051 int j = 0; 00052 while (maybe_prime && _primes[j] * _primes[j] <= candidate) { 00053 if ((_primes[j] * (candidate / _primes[j])) == candidate) { 00054 // This one is not prime. 00055 maybe_prime = false; 00056 } 00057 j++; 00058 nassertr(j < (int)_primes.size(), 0); 00059 } 00060 if (maybe_prime) { 00061 // Hey, we found a prime! 00062 _primes.push_back(candidate); 00063 } 00064 candidate++; 00065 } 00066 00067 return _primes[n]; 00068 }