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

来源:互联网 发布:千寻网络位置服务 编辑:程序博客网 时间:2024/06/11 15:57

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 ofX.  

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_JUDGEfreopen("d:\\OJ\\uva_in.txt", "r", stdin);#endifinit();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;}


0 0
原创粉丝点击