• CF679A.Bear and Prime 100 (交互题)


    input:

    1. yes
    2. no
    3. yes

     output:

    1. 2
    2. 80
    3. 5
    4. composite

    input:

    1. no
    2. yes
    3. no
    4. no
    5. no

    output:

    1. 58
    2. 59
    3. 78
    4. 78
    5. 2
    6. 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,那么生成的数字一定是质数。

    上代码:

    1. #include <iostream>
    2. #include <cstring>
    3. #include <cstdio>
    4. #include <algorithm>
    5. using namespace std;
    6. int cnt;
    7. //int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47};
    8. bool is_prime(int x) {
    9. int num=0;
    10. for(int i=2; i<x; i++)
    11. if(x%i==0)
    12. num++;
    13. if(num==0)
    14. return true;
    15. else
    16. return false;
    17. }
    18. int prime[50];
    19. bool query(int x)
    20. {
    21. cout << x << endl;
    22. string s;
    23. cin >> s;
    24. return s == "yes";
    25. }
    26. int main() {
    27. for(int i=2; i<=50; i++)
    28. {
    29. if(is_prime(i))
    30. prime[++cnt]=i;
    31. }
    32. int num=0;
    33. int now=-1;
    34. for(int i=1; i<=cnt; i++) {
    35. cout<<prime[i]<<endl;
    36. string str;
    37. cin>>str;
    38. if(str=="yes") {
    39. num++;
    40. now=prime[i];
    41. }
    42. }
    43. if(num>=2)
    44. cout<<"composite"<<endl;
    45. else
    46. {
    47. if(now>10||now==-1)
    48. cout<<"prime"<<endl;
    49. else
    50. {
    51. cout<<now*now<<endl;
    52. string str;
    53. cin>>str;
    54. if(str=="yes")
    55. cout<<"composite"<<endl;
    56. else
    57. cout<<"prime"<<endl;
    58. }
    59. }
    60. return 0;
    61. }

  • 相关阅读:
    TMS320C6678 DSP + Xilinx Kintex-7 FPGA核心板硬件参数资源说明分享
    访问者模式
    【LeetCode】No.108. Convert Sorted Array to Binary Search Tree -- Java Version
    数据挖掘note(赵老师语录)
    Vue3+node.js实战项目网易云音乐APP(二)
    【C++干货铺】list的使用 | 模拟实现
    springboot视图渲染技术
    【TB作品】STM32F102C8T6单片机,PWM发生器
    前端面试题10.25
    Rust语言基础:从Hello World开始
  • 原文地址:https://blog.csdn.net/weixin_54562114/article/details/126858983