zoukankan      html  css  js  c++  java
  • nyoj 24-素数距离问题 (素数算法)

    24-素数距离问题


    内存限制:64MB 时间限制:3000ms Special Judge: No
    accepted:21 submit:71

    题目描述:

    现在给出你一些数,要求你写出一个程序,输出这些整数相邻最近的素数,并输出其相距长度。如果左右有等距离长度素数,则输出左侧的值及相应距离。
    如果输入的整数本身就是素数,则输出该素数本身,距离输出0

    输入描述:

    第一行给出测试数据组数N(0<N<=10000)
    接下来的N行每行有一个整数M(0<M<1000000),

    输出描述:

    每行输出两个整数 A B.
    其中A表示离相应测试数据最近的素数,B表示其间的距离。

    样例输入:

    3
    6
    8
    10

    样例输出:

    5 1
    7 1
    11 1

    分析:
      直接根据素数算法判断待判断的数据是否为素数

    核心代码:
    1 bool is_prime(int n)
    2 {
    3     if(n <= 1) return false;
    4     for(int i = 2; i <= sqrt(n); ++ i)
    5         if(n%i == 0) return false;
    6     return true;
    7 }

    C/C++代码实现(AC):

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <cmath>
     4 #include <cstring>
     5 #include <cstdio>
     6 #include <queue>
     7 #include <set>
     8 #include <map>
     9 #include <stack>
    10 
    11 using namespace std;
    12 
    13 bool is_prime(int n)
    14 {
    15     if(n <= 1) return false;
    16     for(int i = 2; i <= sqrt(n); ++ i)
    17         if(n%i == 0) return false;
    18     return true;
    19 }
    20 
    21 int main ()
    22 {
    23     int t;
    24     scanf("%d", &t);
    25     while(t --)
    26     {
    27         int a, l, r;
    28         scanf("%d", &a);
    29         if (is_prime(a))
    30         {
    31             printf("%d 0
    ", a);
    32             continue;
    33         }
    34         for(int i = 1; ; ++ i)
    35         {
    36             if(is_prime(a - i))
    37             {
    38                 printf("%d %d
    ", a-i, i);
    39                 break;
    40             }
    41             if(is_prime(a + i))
    42             {
    43                 printf("%d %d
    ", a+i, i);
    44                 break;
    45             }
    46         }
    47     }
    48     return 0;
    49 }
  • 相关阅读:
    使用samba实现linux和windows文件共享
    使用li列举属性表中的某一属性
    popuptemplate的使用
    html中自动分配界面
    div中移除和添加元素
    使用v-html绑定数据,实现图片的动态转换
    使用js下载数据
    使用FeatureTable对FeatureLayer中的数据进行显示
    使用ant的checkboxGroup将列表信息添加为多选框,并根据多选框的转换进行操作
    arcgis api绘制多个点
  • 原文地址:https://www.cnblogs.com/GetcharZp/p/9065333.html
Copyright © 2011-2022 走看看