-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program to Display Prime Numbers Between Intervals
109 lines (91 loc) · 2.17 KB
/
Program to Display Prime Numbers Between Intervals
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// C Program to Display Prime
// Numbers Between Intervals
#include <stdio.h>
// Driver code
int main()
{
// Declare the variables
int a, b, i, j, flag;
// Ask user to enter lower value
// of interval
printf("Enter lower bound of the interval: ");
// Take input
scanf("%d", &a);
// Ask user to enter upper value
// of interval
printf("Enter upper bound of the interval: ");
// Take input
scanf("%d", &b);
// Print display message
printf("Prime numbers between %d and %d are: ",
a, b);
// Traverse each number in the interval
// with the help of for loop
for (i = a; i <= b; i++)
{
// Skip 0 and 1 as they are
// neither prime nor composite
if (i == 1 || i == 0)
continue;
// flag variable to tell
// if i is prime or not
flag = 1;
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);
}
return 0;
}
----------------------------------------------------
Approach 3: (Using Sieve of Eratosthenes Method)
----------------------------------------------------
// C program to find the prime numbers
// between a given interval using Sieve of Eratosthenes
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void SieveOfEratosthenes(int srt, int n)
{
// Create a boolean array "prime[srt to n]" and
// initialize all entries it as true. A value in
// prime[i] will finally be false if i is Not a prime,
// else true.
bool prime[n + 1];
memset(prime, true, sizeof(prime));
prime[0] = false;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a prime
if (prime[p] == true) {
// Update all multiples of p greater than or
// equal to the square of it numbers which are
// multiple of p and are less than p^2 are
// already been marked.
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p = srt; p <= n; p++)
if (prime[p])
printf("%d ", p);
}
// Driver Code
int main()
{
int srt = 1;
int end = 10;
SieveOfEratosthenes(srt, end);
return 0;
}
// This code is contributed by Susobhan Akhuli