UVa 10139 Factovisors (阶乘能否整除?)

10139 - Factovisors

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1080


水题。


注意在O(log n / log p)时间内求出n!的质因子分解中质数p的指数:(勒让德定理的简化算法)

inline int idx(int n, int p)
{
	int sum = 0;
	while (n)
	{
		n /= p;
		sum += n;
	}
	return sum;
}


完整代码:

/*0.042s*/

#include<cstdio>
#include<cstring>
const int maxn = 1 << 16;

int prime[maxn / 10];
bool vis[maxn];
int cnt;

///求n!的质因子分解中质数p的指数
inline int idx(int n, int p)
{
	int sum = 0;
	while (n)
	{
		n /= p;
		sum += n;
	}
	return sum;
}

bool judge(int n, int m)
{
	if (n >= m) return true;
	int tmp, i;
	for (i = 0; i < cnt && (long long)prime[i] * prime[i] <= m ; ++i)
	{
		if (m % prime[i] == 0)
		{
			tmp = 0;
			do
			{
				m /= prime[i];
				++tmp;
			}
			while (m % prime[i] == 0);
			if (idx(n, prime[i]) < tmp) return false;
		}
	}
	if (m > 1 && n < m) return false; /// 说明m的质因子分解中恰有一个大于maxn的质数
	return true;
}

int main()
{
	int i, j, n, m;
	cnt = 0;
	for (i = 2; i < maxn; ++i)
		if (!vis[i])
		{
			prime[cnt++] = i;
			for (j = i * 2; j < maxn; j += i)
				vis[j] = true;
		}
	while (~scanf("%d%d", &n, &m))
	{
		if (judge(n, m)) printf("%d divides %d!\n", m, n);
		else printf("%d does not divide %d!\n", m, n);
	}
	return 0;
}

你可能感兴趣的:(C++,算法,ACM,uva)