程序代码:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10001
int fac[1024], facCount;
bool isPrime[MAX] = {false};
int primeFactor[10][2], primeFacCount;
int phi[MAX], prime[MAX], priCount = 0;
/*
* MAX 内数据初始化
*/
void initialize()
{
phi[1] = 1;
for (int i = 2; i < MAX; ++i)
{
if (!isPrime[i])
{
prime[priCount++] = i;
phi[i] = i - 1;
}
for (int j = 0; j < priCount; ++j)
{
if (i * prime[j] >= MAX) break;
isPrime[i * prime[j]] = true;
if (i % prime[j] == 0)
{
phi[i * prime[j]] = prime[j] * phi[i];
break;
}
else
{
phi[i * prime[j]] = (prime[j] - 1) * phi[i];
}
}
}
}
/*
* 获取phi
*/
int getPhi(int n)
{
if (n < MAX) return phi[n];
int pos = 0, result = 1;
while (pos < priCount && n >= MAX)
{
while (0 == n % prime[pos])
{
n /= prime[pos], result *= phi[prime[pos]];
}
pos += 1;
}
return pos < priCount ? result * phi[n] : result * (n - 1);
}
/*
* 快速模
*/
long long quickMode(long long a, long long b, long long n)
{
long long ret = 1;
for (; b; b /= 2)
{
if (b & 1) ret = ret * a % n;
a = a * a % n;
}
return ret;
}
/*
* 所有因数
*/
void allFactor(int pos, int result)
{
if (pos >= primeFacCount)
{
fac[facCount++] = result;
return;
}
allFactor(pos + 1, result);
for (int i = 0; i < primeFactor[pos][1]; ++i)
{
result *= primeFactor[pos][0];
allFactor(pos + 1, result);
}
}
/*
* 所有质因数
*/
void initPrimeFactor(int n)
{
int pos = 0;
primeFacCount = 0;
while (pos < priCount && n > 1)
{
if (0 == n % prime[pos])
{
primeFactor[primeFacCount][0] = prime[pos], primeFactor[primeFacCount][1] = 0;
while (0 == n % prime[pos])
{
n /= prime[pos], primeFactor[primeFacCount][1] += 1;
}
primeFacCount++;
}
pos += 1;
}
if (pos >= priCount) primeFactor[primeFacCount][0] = n, primeFactor[primeFacCount++][1] = 1;
}
/*
* 快排传入函数
*/
int cmp(const void *a, const void *b) { return *(int *) a - *(int *) b; }
int main()
{
initialize();
int i, m, n;
freopen("../stdin", "r", stdin);
while (2 == scanf("%d%d", &m, &n) && n > 1)
{
clock_t beg = clock();
int p = n * m - 1, q = getPhi(p);
// printf("φ(%d) = %d = ", p, q);
initPrimeFactor(q);
// for (i = 0; i < primeFacCount; ++i)
// {
// if (i) printf(" * ");
// printf("%d", primeFactor[i][0]);
// if (primeFactor[i][1] > 1) printf(" ^ %d", primeFactor[i][1]);
// }
// printf("\n");
facCount = 0, allFactor(0, 1);
qsort(fac, facCount, sizeof(fac[0]), cmp);
// for (i = 0; i < facCount; ++i) printf("%d%c", fac[i], "\n "[i < facCount - 1]);
for (i = 0; i < facCount; ++i)
{
if (1 == quickMode(n, fac[i], p)) break;
}
printf("%d\n", fac[i]);
printf("all runs %lf seconds\n", (double) (clock() - beg) / CLOCKS_PER_SEC);
}
return 0;
}
[此贴子已经被作者于2017-3-9 17:58编辑过]