C程序 用函数显示两个区间的素数

C程序 用函数显示两个区间的素数

在这里,我们将用以下2种方法建立一个C程序,用函数显示两个区间的质数。

1.使用for循环
2.使用while循环

我们将在上述所有方法中保持相同的输入,并得到相应的输出。

输入:

num1 = 2, num2 = 10

输出:

Prime numbers between 2 and 10 are: 2 3 5 7 

解释: 在给定的区间2(起始极限)和10(终止极限)之间的素数是2 3 5和7。

方法1:使用for循环

// C Program to demonstrate Prime Numbers
// Between Two Intervals Using for 
// loop in a function
  
#include <stdio.h>
  
// user-defined function to check prime number
int checkPrimeNumber(int number)
{
    int i, f = 1;
    
    // condition for finding the
    // prime numbers between the
    // given intervals
    for (i = 2; i <= number / 2; ++i) {
  
        if (number % i == 0) {
            f = 0;
            break;
        }
    }
  
    return f;
}
  
int main()
{
  
    int num1 = 2, num2 = 10, j, f;
  
    printf("Prime numbers between %d and %d are: ", num1,
           num2);
    for (j = num1; j < num2; ++j) {
  
        // if flag is equal to 1 then
        // it is a prime number
        // calling the function
        f = checkPrimeNumber(j);
  
        if (f == 1) {
            
            // printing the result
            printf("%d ", j);
        }
    }
  
    return 0;
}

输出

Prime numbers between 2 and 10 are: 2 3 5 7 

方法2:使用while循环

// C Program to demonstrate Prime Numbers
// Between Two Intervals Using for
// loop in a function
#include <stdio.h>
  
int isPrime(int number)
{
    int i;
    
    // condition for finding the
    // prime numbers between the
    // given intervals
    for (i = 2; i <= number / 2; i++) {
  
        // if the number is divisible 
        // by 1 and self then it
        // is prime number
        if (number % i == 0) {
            return 0;
        }
    }
  
    return 1;
}
  
int main()
{
    int num1 = 2, num2 = 10;
  
    printf("The prime numbers between %d to %d are: ", num1, num2);
  
    while (num1 <= num2) {
  
        // calling the function
        if (isPrime(num1)) {
            
            // printing the result
            printf("%d, ", num1);
        }
  
        num1++;
    }
  
    return 0;
}

输出

The prime numbers between 2 to 10 are: 2, 3, 5, 7, 

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

C语言 实例