
input:
- yes
- no
- yes
output:
- 2
- 80
- 5
- composite
input:
- no
- yes
- no
- no
- no
output:
- 58
- 59
- 78
- 78
- 2
- prime
题目大意:系统会生成一个2~100之间的数y,每次可以由我们给出一个询问,每个询问包含一个数字x,若该数字x为y的因子,则输出yes,否则输出no,我们最多询问20次,最后我们要根据系统的回答来判断y是否为质数,如果是则输出prime,否则输出composite。
解题思路:因为数字y的取值范围为2~100,若y不是素数,那么根据算数基本定理对其进行分解,其包含的质因子范围一定都在2~50之间,所以我们只要筛选出2~50之间的质数,发现总共为15个,然后从小到大每次询问一个质数,统计回答yes的数量,如果数量大于等于2,那么生成的数字一定不是质数,然后对于剩下的情况,当回答yes的数量为1时,记录下此时能整除的质数now,要判断生成的数字是否是某个质数的幂次方,所以我们要再次进行询问now*now是否整除y,如果回答yes,那么就不是质数,否则是质数,如果yes的数量为0,那么生成的数字一定是质数。
上代码:
- #include <iostream>
- #include <cstring>
- #include <cstdio>
- #include <algorithm>
- using namespace std;
- int cnt;
- //int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
- bool is_prime(int x) {
- int num=0;
- for(int i=2; i<x; i++)
- if(x%i==0)
- num++;
- if(num==0)
- return true;
- else
- return false;
- }
- int prime[50];
- bool query(int x)
- {
- cout << x << endl;
- string s;
- cin >> s;
- return s == "yes";
- }
- int main() {
- for(int i=2; i<=50; i++)
- {
- if(is_prime(i))
- prime[++cnt]=i;
- }
- int num=0;
- int now=-1;
- for(int i=1; i<=cnt; i++) {
- cout<<prime[i]<<endl;
- string str;
- cin>>str;
- if(str=="yes") {
- num++;
- now=prime[i];
- }
- }
- if(num>=2)
- cout<<"composite"<<endl;
- else
- {
- if(now>10||now==-1)
- cout<<"prime"<<endl;
- else
- {
- cout<<now*now<<endl;
- string str;
- cin>>str;
- if(str=="yes")
- cout<<"composite"<<endl;
- else
- cout<<"prime"<<endl;
- }
- }
- return 0;
- }