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!
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 withN>1,000,000 is no more than 100.
For each case, output the requested M, or output 0 if no solution exists.
3 4 5 6
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;
}原文地址:http://blog.csdn.net/u013749862/article/details/41406961