# Queries for Composite numbers in subarray (With Point Updates)

Given an array of N integers, the task is to perform the following two operations on the given array:

query(start, end) : Print the number of Composite numbers in the subarray from start to end
update(i, x) : update the value at index i to x, i.e arr[i] = x

Examples:

```Input : arr = {1, 12, 3, 5, 17, 9}
Query 1: query(start = 0, end = 4)
Query 2: update(i = 3, x = 6)
Query 3: query(start = 0, end = 4)
Output :1
2
Explanation
In Query 1, the subarray [0...4]
has 1 Composite number viz. {12}

In Query 2, the value at index 3
is updated to 6, the array arr now is, {1, 12, 3,
6, 7, 9}
In Query 3, the subarray [0...4]
has 2 Composite Numbers viz. {12, 6}
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Since, we need to handle both range queries and point updates, an efficient method is to use a segment tree to solve the problem. A segment tree is best suited for this purpose.

We can use Sieve of Eratosthenes to preprocess all the primes till the maximum value that arri can take, say MAX. The time complexity for this operation will be O(MAX log(log(MAX))).

Building the segment tree:
The problem can be reduced to subarray sum using segment tree.

Now, we can build the segment tree where a leaf node is represented as either 0 (if it is a prime number) or 1 (if it is a composite number).

The internal nodes of the segment tree equal to the sum of its child nodes, thus a node represents the total composite numbers in the range from L to R where the range L to R falls under this node and the sub-tree below it.

Whenever we get a query from start to end, then we can query the segment tree for the sum of nodes in range start to end, which in turn represent the number of composites in range start to end.

If we need to perform a point update and update the value at index i to x, then we check for the following cases:

Let the old value of arri be y and the new value be x.

Case 1: If x and y both are composites.
Count of composites in the subarray does not change so we just update array and donot
modify the segment tree

Case 2: If x and y both are primes.
Count of composites in the subarray does not change so we just update array and donot
modify the segment tree

Case 3: If y is composite but x is prime.
Count of composite numbers in the subarray decreases so we update array and add -1 to every
range, the index i which is to be updated, is a part of in the segment tree

Case 4: If y is prime but x is composite.
Count of composite numbers in the subarray increases so we update array and add 1 to every
range, the index i which is to be updated, is a part of in the segment tree

Below is the implementation of the above approach:

 `// C++ program to find number of composite numbers in a ` `// subarray and performing updates ` ` `  `#include ` `using` `namespace` `std; ` ` `  `#define MAX 1000 ` ` `  `// Function to calculate primes upto MAX ` `// using sieve of Eratosthenes ` `void` `sieveOfEratosthenes(``bool` `isPrime[]) ` `{ ` `    ``isPrime[1] = ``true``; ` ` `  `    ``for` `(``int` `p = 2; p * p <= MAX; p++) { ` ` `  `        ``// If prime[p] is not changed, then ` `        ``// it is a prime ` `        ``if` `(isPrime[p] == ``true``) { ` ` `  `            ``// Update all multiples of p ` `            ``for` `(``int` `i = p * 2; i <= MAX; i += p) ` `                ``isPrime[i] = ``false``; ` `        ``} ` `    ``} ` `} ` ` `  `// A utility function to get the middle ` `// index from corner indexes. ` `int` `getMid(``int` `s, ``int` `e) ` `{ ` `    ``return` `s + (e - s) / 2; ` `} ` ` `  `/*  A recursive function to get the number of composites  ` `    ``in a given range of array indexes. The following are  ` `    ``parameters for this function. ` ` `  `    ``st --> Pointer to segment tree ` `    ``index --> Index of current node in the segment tree.  ` `              ``Initially 0 is passed as root is always  ` `              ``at index 0. ` `    ``ss & se --> Starting and ending indexes of the  ` `                ``segment represented by current node,  ` `                ``i.e., st[index] ` `    ``qs & qe --> Starting and ending indexes of  ` `    ``query range  ` `*/` `int` `queryCompositesUtil(``int``* st, ``int` `ss, ``int` `se, ``int` `qs, ` `                        ``int` `qe, ``int` `index) ` `{ ` `    ``// If segment of this node is a part of given range, ` `    ``// then return the number of composites ` `    ``// in the segment ` `    ``if` `(qs <= ss && qe >= se) ` `        ``return` `st[index]; ` ` `  `    ``// If segment of this node is ` `    ``// outside the given range ` `    ``if` `(se < qs || ss > qe) ` `        ``return` `0; ` ` `  `    ``// If a part of this segment ` `    ``// overlaps with the given range ` `    ``int` `mid = getMid(ss, se); ` `    ``return` `queryCompositesUtil(st, ss, mid, qs, qe, 2 * index + 1) ` `           ``+ queryCompositesUtil(st, mid + 1, se, qs, qe, 2 * index + 2); ` `} ` ` `  `/*  A recursive function to update the nodes which  ` `    ``have the given index in their range. The following  ` `    ``are parameters st, si, ss and se are same as getSumUtil() ` `     `  `    ``i --> index of the element to be updated. This index is  ` `          ``in input array. ` `    ``diff --> Value to be added to all nodes which  ` `          ``have i in range  ` `*/` `void` `updateValueUtil(``int``* st, ``int` `ss, ``int` `se, ``int` `i, ` `                     ``int` `diff, ``int` `si) ` `{ ` `    ``// Base Case: If the input index ` `    ``// lies outside the range of ` `    ``// this segment ` `    ``if` `(i < ss || i > se) ` `        ``return``; ` ` `  `    ``// If the input index is in range of ` `    ``// this node, then update the value of ` `    ``// the node and its children ` `    ``st[si] = st[si] + diff; ` ` `  `    ``if` `(se != ss) { ` `        ``int` `mid = getMid(ss, se); ` `        ``updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); ` `        ``updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); ` `    ``} ` `} ` ` `  `// The function to update a value in input ` `// array and segment tree. It uses updateValueUtil() ` `// to update the value in segment tree ` `void` `updateValue(``int` `arr[], ``int``* st, ``int` `n, ``int` `i, ` `                 ``int` `new_val, ``bool` `isPrime[]) ` `{ ` `    ``// Check for erroneous input index ` `    ``if` `(i < 0 || i > n - 1) { ` `        ``printf``(``"Invalid Input"``); ` `        ``return``; ` `    ``} ` ` `  `    ``int` `diff, oldValue; ` ` `  `    ``oldValue = arr[i]; ` ` `  `    ``// Update the value in array ` `    ``arr[i] = new_val; ` ` `  `    ``// Case 1: Old and new values both are primes ` `    ``if` `(isPrime[oldValue] && isPrime[new_val]) ` `        ``return``; ` ` `  `    ``// Case 2: Old and new values both composite ` `    ``if` `((!isPrime[oldValue]) && (!isPrime[new_val])) ` `        ``return``; ` ` `  `    ``// Case 3: Old value was composite, new value is prime ` `    ``if` `(!isPrime[oldValue] && isPrime[new_val]) { ` `        ``diff = -1; ` `    ``} ` ` `  `    ``// Case 4: Old value was prime, new_val is composite ` `    ``if` `(isPrime[oldValue] && !isPrime[new_val]) { ` `        ``diff = 1; ` `    ``} ` ` `  `    ``// Update the values of nodes in segment tree ` `    ``updateValueUtil(st, 0, n - 1, i, diff, 0); ` `} ` ` `  `// Return number of composite numbers in range ` `// from index qs (query start) to qe (query end). ` `// It mainly uses queryCompositesUtil() ` `void` `queryComposites(``int``* st, ``int` `n, ``int` `qs, ``int` `qe) ` `{ ` `    ``int` `compositesInRange = queryCompositesUtil(st, 0, n - 1, qs, qe, 0); ` ` `  `    ``cout << ``"Number of Composites in subarray from "` `<< qs ` `         ``<< ``" to "` `<< qe << ``" = "` `<< compositesInRange << ``"\n"``; ` `} ` ` `  `// A recursive function that constructs Segment Tree ` `// for array[ss..se]. ` `// si is index of current node in segment tree st ` `int` `constructSTUtil(``int` `arr[], ``int` `ss, ``int` `se, ``int``* st, ` `                    ``int` `si, ``bool` `isPrime[]) ` `{ ` `    ``// If there is one element in array, check if it ` `    ``// is prime then store 1 in the segment tree else ` `    ``// store 0 and return ` `    ``if` `(ss == se) { ` ` `  `        ``// if arr[ss] is composite ` `        ``if` `(!isPrime[arr[ss]]) ` `            ``st[si] = 1; ` `        ``else` `            ``st[si] = 0; ` ` `  `        ``return` `st[si]; ` `    ``} ` ` `  `    ``// If there are more than one elements, then recur ` `    ``// for left and right subtrees and store the sum ` `    ``// of the two values in this node ` `    ``int` `mid = getMid(ss, se); ` `    ``st[si] = constructSTUtil(arr, ss, mid, st, ` `                             ``si * 2 + 1, isPrime) ` `             ``+ constructSTUtil(arr, mid + 1, se, st, ` `                               ``si * 2 + 2, isPrime); ` `    ``return` `st[si]; ` `} ` ` `  `/*  Function to construct segment tree from given array.  ` `    ``This function allocates memory for segment tree and ` `    ``calls constructSTUtil() to fill the allocated memory */` `int``* constructST(``int` `arr[], ``int` `n, ``bool` `isPrime[]) ` `{ ` `    ``// Allocate memory for segment tree ` ` `  `    ``// Height of segment tree ` `    ``int` `x = (``int``)(``ceil``(log2(n))); ` ` `  `    ``// Maximum size of segment tree ` `    ``int` `max_size = 2 * (``int``)``pow``(2, x) - 1; ` ` `  `    ``int``* st = ``new` `int``[max_size]; ` ` `  `    ``// Fill the allocated memory st ` `    ``constructSTUtil(arr, 0, n - 1, st, 0, isPrime); ` ` `  `    ``// Return the constructed segment tree ` `    ``return` `st; ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` ` `  `    ``int` `arr[] = { 1, 12, 3, 5, 17, 9 }; ` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]); ` ` `  `    ``/*  Preprocess all primes till MAX. ` `        ``Create a boolean array "isPrime[0..MAX]". ` `        ``A value in prime[i] will finally be false  ` `        ``if i is composite, else true.  ` `    ``*/` `    ``bool` `isPrime[MAX + 1]; ` `    ``memset``(isPrime, ``true``, ``sizeof` `isPrime); ` `    ``sieveOfEratosthenes(isPrime); ` ` `  `    ``// Build segment tree from given array ` `    ``int``* st = constructST(arr, n, isPrime); ` ` `  `    ``// Query 1: Query(start = 0, end = 4) ` `    ``int` `start = 0; ` `    ``int` `end = 4; ` `    ``queryComposites(st, n, start, end); ` ` `  `    ``// Query 2: Update(i = 3, x = 6), i.e Update ` `    ``// a[i] to x ` `    ``int` `i = 3; ` `    ``int` `x = 6; ` `    ``updateValue(arr, st, n, i, x, isPrime); ` ` `  `    ``// Query 3: Query(start = 0, end = 4) ` `    ``start = 0; ` `    ``end = 4; ` `    ``queryComposites(st, n, start, end); ` ` `  `    ``return` `0; ` `} `

Output:

```Number of Composites in subarray from 0 to 4 = 1
Number of Composites in subarray from 0 to 4 = 2
```

The time complexity of each query and update is O(logn) and that of building the segment tree is O(n)

Note: Here, the time complexity of pre-processing primes till MAX using the sieve of Eratosthenes is O(MAX log(log(MAX))) where MAX is the maximum value arri can take.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.