Menu Close

C语言练习:判断两个数之间的数是否是质数(素数)

素数又称质数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数(也可定义为只有1与该数本身两个正因数的数)。

一个自然数(如1、2、3、4、5、6等)若恰有两个正约数(1及此数本身),则称之为素数。大于1的自然数若不是素数,则称之为合数

#include <stdio.h>

int main() {
   int low, high, i, flag;
   printf("Enter two numbers(intervals): ");
   scanf("%d %d", &low, &high);
   printf("Prime numbers between %d and %d are: ", low, high);

   // iteration until low is not equal to high
   while (low < high) {
      flag = 0;

      // ignore numbers less than 2
      if (low <= 1) {
         ++low;
         continue;
      }

      // if low is a non-prime number, flag will be 1
      for (i = 2; i <= low / 2; ++i) {

         if (low % i == 0) {
            flag = 1;
            break;
         }
      }

      if (flag == 0)
         printf("%d ", low);

      // to check prime for the next number
      // increase low by 1
      ++low;
   }

   return 0;
}
Enter two numbers(intervals): 20
50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
READ  C语言程序显示打印出矩阵的转置
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C 决策和循环语句

Related Posts