📜  C / C ++程序查找给定范围之间的素数

📅  最后修改于: 2021-05-31 22:48:05             🧑  作者: Mango

给定两个数字LR,任务是找到LR之间的质数。

例子:

方法:他的想法是从[L,R]范围内进行迭代,并检查给定范围内的任何数字是否为质数。如果是,则打印该数字并检查下一个数字,直到我们迭代所有数字为止。

下面执行上述方法:

C
// C program to find the prime numbers
// between a given interval
#include 
  
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
    int i, j, flag;
  
    // Traverse each number in the
    // interval with the help of for loop
    for (i = L; i <= R; i++) {
  
        // Skip 0 and 1 as they are
        // niether prime nor composite
        if (i == 1 || i == 0)
            continue;
  
        // flag variable to tell
        // if i is prime or not
        flag = 1;
  
        // Iterate to check if i is prime
        // or not
        for (j = 2; j <= i / 2; ++j) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }
  
        // flag = 1 means i is prime
        // and flag = 0 means i is not prime
        if (flag == 1)
            printf("%d ", i);
    }
}
  
// Driver Code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
  
    // Function Call
    primeInRange(L, R);
  
    return 0;
}


C++
// C++ program to find the prime numbers
// between a given interval
#include 
using namespace std;
  
// Function for print prime
// number in given range
void primeInRange(int L, int R)
{
    int flag;
  
    // Traverse each number in the
    // interval with the help of for loop
    for (int i = L; i <= R; i++) {
  
        // Skip 0 and 1 as they are
        // niether prime nor composite
        if (i == 1 || i == 0)
            continue;
  
        // flag variable to tell
        // if i is prime or not
        flag = 1;
  
        // Iterate to check if i is prime
        // or not
        for (int j = 2; j <= i / 2; ++j) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }
  
        // flag = 1 means i is prime
        // and flag = 0 means i is not prime
        if (flag == 1)
            cout << i << " ";
    }
}
  
// Driver Code
int main()
{
    // Given Range
    int L = 1;
    int R = 10;
  
    // Function Call
    primeInRange(L, R);
  
    return 0;
}


输出:
2 3 5 7

时间复杂度: O((RL)* N) ,其中N是数字,L和R是给定范围。
辅助空间: O(1)