zoukankan      html  css  js  c++  java
  • PAT 07-3 求素数

    求素数,这是一个“古老”的问题,每个学过编程的人都应该碰到过,这里是求第M+1到第N个素数,这么经典的问题,当然得给它写上一笔,下面是题设要求及代码实现

     1 /*
     2     Name: 
     3     Copyright: 
     4     Author: 
     5     Date: 01/04/15 19:19
     6     Description: 
     7 令Pi表示第i个素数。现任给两个正整数M <= N <= 104,请输出PM到PN的所有素数。
     8 
     9 输入格式:
    10 
    11 输入在一行中给出M和N,其间以空格分隔。
    12 
    13 输出格式:
    14 
    15 输出从PM到PN的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。
    16 
    17 输入样例:
    18 5 27
    19 输出样例:
    20 11 13 17 19 23 29 31 37 41 43
    21 47 53 59 61 67 71 73 79 83 89
    22 97 101 103
    23 */
    24 
    25 #include <stdio.h>
    26 #include <math.h>
    27 #include <stdbool.h>
    28 
    29 void print(int M, int N);
    30 bool isprime(int n);
    31 
    32 int main()
    33 {
    34     int M, N;
    35     
    36     scanf("%d%d", &M, &N);
    37     print(M, N);
    38     
    39     return 0;
    40 }
    41 
    42 void print(int M, int N)
    43 {
    44     int i, cnt;
    45     
    46     for(i = 2, cnt = 0; cnt < N; i++)
    47     {
    48         if(isprime(i))
    49         {
    50             cnt++;
    51             
    52             if(cnt >= M)
    53             {
    54                 printf("%d", i);
    55                 if((cnt - M + 1) % 10 != 0 && cnt < N)
    56                         printf(" ");
    57                 else
    58                     printf("
    ");
    59             }
    60         }
    61     }
    62 }
    63 
    64 bool isprime(int n)
    65 {
    66     int i, tmp;
    67     
    68     tmp = sqrt(n);
    69     for(i = 2; i <= tmp; i++)
    70     {
    71         if(n % i == 0)
    72             return false;
    73     }
    74     
    75     return true;
    76 }
  • 相关阅读:
    Windows Server 2012 64bit RMAN异机不完全恢复(迁移)
    dbms_jobs vs. dbms_scheduler_jobs
    Migrating from dbms_job to dbms_scheduler
    ORA-12537: TNS:connection closed
    win7 ins 30131 oracle 12c
    Vector源码分析
    LinkedList源码分析
    ArrayList源码分析
    jsp 显示日期
    Spring data redis 使用 pipelined 批量操作
  • 原文地址:https://www.cnblogs.com/qingkai/p/4385360.html
Copyright © 2011-2022 走看看