feat(numerics): add is_prime function

Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
Leonardo de Moura 2013-10-16 17:25:08 -07:00
parent 1097bbfb22
commit 39f68ed0d6
3 changed files with 33 additions and 3 deletions

View file

@ -24,8 +24,20 @@ static void tst1() {
std::cout << "\n";
}
static void tst2() {
prime_iterator it;
for (unsigned i = 0; i < 100000; i++) {
uint64 p = it.next();
lean_assert(is_prime(p));
if (i % 1000 == 0)
std::cout << p << " "; std::cout.flush();
}
std::cout << "\n";
}
int main() {
tst1();
tst2();
return has_violations() ? 1 : 0;
}

View file

@ -106,4 +106,21 @@ uint64 prime_iterator::next() {
return g_prime_generator(idx);
}
}
bool is_prime(uint64 p) {
// Naive is_prime implementation that tests for divisors up to sqrt(p),
// and skips multiples of 2 and 3
if (p == 2 || p == 3)
return true;
uint64 i = 5;
while (i*i <= p) {
if (p % i == 0)
return false;
i += 2;
if (p % i == 0)
return false;
i += 3;
}
return true;
}
}

View file

@ -7,13 +7,14 @@ Author: Leonardo de Moura
#include "util/uint64.h"
namespace lean {
/**
\brief Prime number iterator. It can be used to enumerate the first LEAN_PRIME_LIST_MAX_SIZE primes.
*/
/** \brief Prime number iterator. It can be used to enumerate the first LEAN_PRIME_LIST_MAX_SIZE primes. */
class prime_iterator {
unsigned m_idx;
public:
prime_iterator();
/** \brief Return the next prime */
uint64 next();
};
/** \brief Return true iff \c p is a prime number. */
bool is_prime(uint64 p);
}