C++
Machine i5-760 @ 2.8Ghz, only one core used
Numbers found in 5 seconds: 129
#define WIN32_MEAN_AND_LEAN
#include <windows.h>
#include <iostream>
using namespace std;
bool IsPrime (int v)
{
bool
is_prime = true;
for (int i = 3, i2 = 9 ; i2 < v ; ++i, i2 += i + i + 1)
{
if (v % i == 0)
{
is_prime = false;
break;
}
}
return is_prime;
}
int Prime (int i, int &i2)
{
static int
primes [10000] = {2, 3, 5},
primes2 [10000] = {4, 9, 25},
num_primes = 3;
while (i >= num_primes)
{
int
v = primes [num_primes - 1];
do
{
v += 2;
} while (!IsPrime (v));
primes [num_primes] = v;
primes2 [num_primes] = v * v;
++num_primes;
}
i2 = primes2 [i];
return primes [i];
}
bool IsCarmichael (int n)
{
if (n < 2)
{
return false;
}
int
k = n--,
i2 = 4;
for (int i = 1, p = 2 ; i2 <= k ; p = Prime (i++, i2))
{
if (k % p == 0)
{
k /= p;
if (k % p == 0 || n % (p - 1) != 0)
{
return false;
}
i = 0;
}
}
return --k != n && n % k == 0;
}
int main ()
{
DWORD
end = GetTickCount () + 5000;
int
count = 0,
n = 561;
while (GetTickCount () < end)
{
for (int i = 0 ; i < 1000 ; ++i)
{
if (IsCarmichael (n))
{
++count;
cout << n << endl;
}
++n;
}
}
cout << count << " Carmichael numbers found out of " << (n - 561) << " values tested." << endl;
}
3@JB: I for one usually accept the shortest answer only after a week or so. Also I doubt that this site will be that acceptance-heavy as SO. – Joey – 2011-02-12T18:05:10.607
10 seconds seems an awfully short time for this problem. Unless you hardcode the answer... – Keith Randall – 2011-02-14T03:18:16.387
Is multi-threading allowed? – Magic Octopus Urn – 2016-12-22T19:56:24.367