Alexandra and Prime Numbers(思维)

时间:2023-03-09 17:55:10
Alexandra and Prime Numbers(思维)

Alexandra and Prime Numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1658    Accepted Submission(s): 565

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

题解:让找最小的正整数M使N/M是素数;

水暴力,但是完全暴力会超,就想着折半找,先找这个最小正整数,如果不行就找素数;都找到sqrt(N)结束,这样就省了好多时间;

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
bool is_prim(int x){
if(x == )return false;
for(int i = ; i <= sqrt(x); i++){
if(x % i == )return false;
}
return true;
}
int main(){
int N;
while(~scanf("%d",&N)){
if(N == || N == ){
puts("");continue;
}
int i;
int ans = ;
for(i = ; i <= sqrt(N); i++){
if(N % i == && is_prim(N/i)){
ans = i;
break;
}
}
if(ans){
printf("%d\n",ans);continue;
}
for(int j = sqrt(N); j > ; j--){
if(N % j == && is_prim(j)){
ans = N / j;
break;
}
}
printf("%d\n",ans);
}
return ;
}