Alexandra and Prime Numbers
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1614 Accepted Submission(s): 193
Problem Description
Alexandra has a little brother. He is new to programming. One day he is solving the following problem: Given an positive integer N, judge whether N is prime. The problem above is quite easy, so Alexandra gave him a new task: Given a positive integer N, find the minimal positive integer M, such that N/M is prime. If such M doesn't exist, output 0. Help him!
Input
There are multiple test cases (no more than 1,000). Each case contains only one positive integer N. N≤1,000,000,000 . Number of cases with N>1,000,000 is no more than 100.
Output
For each case, output the requested M, or output 0 if no solution exists.
Sample Input
3 4 5 6
Sample Output
1 2 1 2
【分析】:刚刚拿到这题的第一感觉就是用素数的相关操作去处理这道题,然后超时但还是不死心,不停的优化。但本题和其他的素数不一样的地方就是这道题它求的是N/M,所以既然涉及到除法,其实我们还是用另外一种方法去处理这道题,那就是质因数分解。
质因数分解:就是把一个合数分解成几个素数相乘的形式。例如:
48 = 2*2*2*3
58 = 2*3*3*3
由此我们可以将N一直除以一个比它自己本身小的质数,按照质因数分解的方法,不停的进行分解,我们要找到一个分解出的最大的素数P,因为只有这样,我们才能使得M最小。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <bitset>
#include <cassert>
using namespace std;
typedef long long LL;
const int N = 50;
int n;
void work() {
int i , m , x = 0;
m = n;
for (i = 2 ; i * i <= n ; ++ i) {
if (n % i == 0) {
while (n % i == 0)
n /= i;
x = max(x , i);
}
}
if (n > 1)
x = max(x , n);
printf("%d\n" , x ? m / x : 0);
}
int main() {
while (~scanf("%d",&n))
work();
return 0;
}
下面这个普通的使用素数的方法,无论如何都过不了,不知道是哪组数据的问题。暂时没有弄清楚。
#include<iostream>
#include<math.h>
#include<string.h>
#include<stdio.h>
using namespace std;
#define N 50001
bool isprime[N];
__int64 prime[N],nprime;
void doprime()
{
__int64 i,j; // !!注意
nprime = 1;
memset(isprime,true,sizeof(isprime));
isprime[1] = 0;
for(i = 2;i<=N;i++)
{
if(isprime[i])
{
prime[nprime++] = i;
for(j = i*i;j<=N;j+=i)
{
isprime[j] = false;
}
}
}
}
/*这是一段高效的素数判断的代码。
bool isp(int n)
{
int i,k = (int)sqrt(double(n));
for(i = 1;prime[i]<=k;i++)
if(n%prime[i] == 0)
return 0;
return 1;
}
*/
int main()
{
__int64 a;
doprime();
while(~scanf("%I64d",&a))
{
int flag = 0;
if(a==1)
{
printf("0\n");
continue;
}
for(int i = 50000;i>=1;i--)
{
if(prime[i]&&a%prime[i] == 0)
{
printf("%I64d\n",a/prime[i]);
flag = 1;
break;
}
}
if(flag == 0)
printf("0\n");
}
return 0;
}