forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompositeprimeno.cpp
More file actions
67 lines (53 loc) · 1.4 KB
/
compositeprimeno.cpp
File metadata and controls
67 lines (53 loc) · 1.4 KB
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
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000
int prime[MAX + 1];
void updatePrimes()
{
// prime[] marks all prime numbers as true
// so prime[i] = 1 if ith number is a prime
// Initialization
for (int i = 2; i <= MAX; i++) {
prime[i] = 1;
}
// 0 and 1 are not primes
prime[0] = prime[1] = 0;
// Mark composite numbers as false
// and prime numbers as true
for (int i = 2; i * i <= MAX; i++) {
if (prime[i] == 1) {
for (int j = i * i; j <= MAX; j += i) {
prime[j] = 0;
}
}
}
for (int i = 1; i <= MAX; i++) {
prime[i] += prime[i - 1];
}
}
int getDifference(int l, int r)
{
// Total elements in the range
int total = r - l + 1;
// Count of primes in the range [l, r]
int primes = prime[r] - prime[l - 1];
// Count of composite numbers
// in the range [l, r]
int composites = total - primes;
// Return the sbsolute difference
return (abs(primes - composites));
}
// Driver code
int main()
{
int queries[][2] = { { 1, 10 }, { 5, 30 } };
int q = sizeof(queries) / sizeof(queries[0]);
updatePrimes();
// Perform queries
for (int i = 0; i < q; i++)
cout << getDifference(queries[i][0],
queries[i][1])
<< endl;
return 0;
}