给定两个数字L和R,任务是找到L和R之间的质数。
例子:
Input: L = 1, R = 10
Output: 2 3 5 7Explanation:
Prime number between the 1 and 10 are 2, 3, 5, and 7
Input: L = 30, R = 40
Output: 31 37
方法:他的想法是从[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)