键入一个数,求从1到该数之间的素数

2019-10-08  本文已影响0人  程序员蜗牛

题目:

从键盘读入一个整数,求出1到该数之间的全部素数。输出格式为:每五个数字为一行,最后一行输出该批素数的总个数。

实现代码:

# include<stdio.h>

int main(int argc,char *argv[]){
  int up_limit, m, n , i = 1, k = 1;
  scanf("%d",&up_limit);
  printf("%d\t",2);
  for (m = 3; m <= up_limit; m++){
    for (n = 2; n < m; n++){
      if ( m % n == 0){
        k = 0;
        break;
      }
      else if(m % n != 0){
        k = 1;
        continue;
      }
    }
    if ( k == 1){
      printf("%d\t",m);
      i++;
      if ( i % 5 == 0)
      printf("\n");
      }
  }
  if (i % 5 == 0)
    printf("The number of prime numbers within %d is %d.\n",up_limit, i);
  else
    printf("\nThe number of prime numbers within %d is %d.\n",up_limit, i);
  return 0;
}
上一篇下一篇

猜你喜欢

热点阅读