SGU113 水题 Easy Problem

来源:互联网 发布:服务器 linux 编辑:程序博客网 时间:2024/05/17 06:03

问题:判断一个数是否是两个质数的乘积。

Problem: Nearly prime number is an integer positive number for which it is possible to find such primes P1 and P2 that given number is equal to P1*P2. There is given a sequence on N integer positive numbers, you are to write a program that prints “Yes” if given number is nearly prime and “No” otherwise.

解法:筛法求质数,再枚举。枚举时要用O(Sqrt(N))的复杂度判断另一个质数。

Solution: Obtain prime numbers by sieving method, then enumerate them. Please note that you need to use the method of complexity of O(Sqrt(N)) to judge the other number whether it is a prime number in case it is very large.

#include <iostream>#include <stdio.h>#include <cmath>#include <cstring>#include <math.h>using namespace std;int n,m,pnum,p[100100];bool f[1000100];bool isprime(int x) {     if (x<2) return 0;     for (int i=2;i*i<=x;i++)         if (x%i==0) return 0;     return 1;}int main() {    pnum = 0;    memset(f,0,sizeof(f));    f[1] = true;    for (int i=2;i<=1000010;i++)        if (!f[i]) {           pnum++;           p[pnum] = i;           for (int j=i+i;j<=1000010;j+=i) f[j] = true;        }            scanf("%d",&n);    while (n--) {          bool ans = false;          scanf("%d",&m);          for (int i=1;i<=pnum;i++) {              if (p[i]*p[i]>m) break;              if ((m%p[i]==0) && isprime(m/p[i])) {                    ans = true;                    break;              }          }          if (ans) printf("Yes\n");          else printf("No\n");    }    return 0;}



0 0
原创粉丝点击