📌  相关文章
📜  C程序显示两个时间间隔之间的质数

📅  最后修改于: 2020-10-04 11:43:24             🧑  作者: Mango

在此示例中,您将学习如何打印用户输入的两个数字之间的所有素数。

显示两个间隔之间的素数
#include 

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

在此程序中, while循环被迭代( high-low-1 )次。

在每次迭代中,检查low是否是素数,并将low的值增加1直到low等于high

访问此页面以了解有关如何检查数字是否为质数的更多信息。

如果用户首先输入较大的数字,则上述程序将无法正常工作。您可以通过交换数字来解决此问题。


首先输入较大的数字时显示质数
#include 

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

   // swap numbers if low is greather than high
   if (low > high) {
      temp = low;
      low = high;
      high = temp;
   }

   printf("Prime numbers between %d and %d are: ", low, high);
   while (low < high) {
      flag = 0;

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

      for (i = 2; i <= low / 2; ++i) {
         if (low % i == 0) {
            flag = 1;
            break;
         }
      }
      if (flag == 0)
         printf("%d ", low);
      ++low;
   }

   return 0;
}

访问此页面以了解如何通过创建用户定义的函数来显示两个时间间隔之间的所有素数