UVa10856 - Recover Factorial(预处理+二分)

Factorial numbersare expressible as the multiplication of zero or more prime numbers. Forexample 4! (Factorial of 4) can be expressed as follows:-

4! = 2 x 2 x 2 x 3(total number of prime factor is 4)

Given N, thenumber of prime factors in X! (Factorial of X),you have to findthe minimum possible value of X.  

Input

There may be at most1000 test cases. Each test case consists of one non-negative integerN<=10000001in each line. A negative integer marks the end of input, which should not be  processed by your program.

Output

For every test caseexcept last one print either “Case #: X!” if solution exist or“Case#: Not possible.” if no solution exist in each line (without the quotes).Here ‘#’ represents serial of test case starting from 1. Look at sample outputfor details.

Sample Input

4
240
241
-1

Sample Output

Case 1: 4!
Case 2: 101!
Case 3: Not possible.


从2至x计算其质因数的个数,然后用n减去相应的个数,直至为0,这样做会超时

先预处理,然后用二分法查找

#include <cstdio>
#include <cstring>

using namespace std;

const int N = 2705000;
const int SQRTN = 1645;

unsigned int f[N + 1];

void init();
int solve(int n);

int main()
{
	#ifndef ONLINE_JUDGE
		freopen("d:\\OJ\\uva_in.txt", "r", stdin);
	#endif
	
	init();
	
	int t = 1, n;
	
	while (scanf("%d", &n) == 1 && n >= 0) {
		int ans = solve(n);
		if (ans == -1) {
			printf("Case %d: Not possible.\n", t++);
		} else 
			printf("Case %d: %d!\n", t++, solve(n));
	}
	
	return 0;
}

void init()
{
	unsigned int i, j, k;
	
	memset(f, 0x00, sizeof(f));
	
	for (i = 2; i <= N; i++) {
		if (f[i]) continue;
		
		for (j = i; j <= N; j += i) {
			f[j]++;
		}
		
		if (i > SQRTN) continue;
		
		for (k = i * i; ; k *= i) {
			for (j = k; j <= N; j += k) f[j]++;
			
			if ((long long)k * (long long)i > (long long)N) break;
		}
	}
	
	for (i = 1; i <= N; i++) {
		f[i] += f[i - 1];
	}
}

int solve(int n)
{
	int a, b, c;
	
	if (n == 0) return 0;
	
	for (a = 0, b = N; a <= b;) {
		c = (a + b) >> 1;
		if (f[c] < n) {
			a = c + 1;
		} else if (f[c] > n) {
			b = c - 1;
		} else return c;
	}
	
	return -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值