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使得 N/M 是一个素数。
【分析】:刚刚拿到这题的第一感觉就是用素数的相关操作去处理这道题,然后超时但还是不死心,不停的优化。但本题和其他的素数不一样的地方就是这道题它求的是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; }
时间: 2024-10-06 00:10:41