You are reading the article Working Of Substr() Function In C++ updated in November 2023 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Working Of Substr() Function In C++
Introduction to C++ SubstringIn C++, a substring refers to a part of a string. To retrieve a substring from a given string in C++, the substr() function is used. It takes the two parameters position and length, where position represents the starting position of the substring in the given string, and length represents the number of characters in the substring to be retrieved from the given string. This substr() function returns the substring extracted from the given string starting from the specified position up to the number of characters from the starting position specified as length.
Start Your Free Software Development Course
Syntax:
substr(position, length)Where “position” represents the starting position of the substring in the given string, and “length” represents the number of characters in the substring to retrieve from the given string.
Working of Substr() Function in C++Working of substr() function in C++ is as follows:
In C++, we use the substr() function to retrieve a substring from a given string. A substring in C++ refers to a part of the string.
The substr() function takes two parameters: position and length.
The parameter position represents the starting position of the substring in the given string.
The parameter length represents the number of characters in the substring to retrieve from the given string.
The substr() function returns the substring extracted from the given string starting from the specified position up to the number of characters from the starting position specified as length.
Examples of C++ SubstringFollowing are the examples:
Example #1C++ program to demonstrate substr function that returns the substring extracted from the given string starting from the specified position up to the number of characters from the starting position specified as length:
Code:
using namespace std; int main() { string strone = "Welcome to C++_learning"; string strtwo = strone.substr(11, 12); cout << "The given string is: " << strone << "n" <<endl; cout << "The substring extracted from the given string is: " << strtwo << "n" << endl; return 0; }Output:
In the above program, we have included the headers iostream and string, allowing us to use cin, court, and substr. The program executes the primary method and defines a string variable, “strone,” to store the original string from which a substring will be extracted. Using the substr function, the program extracts a substring from the string “strone,” starting from a specified position and extending for a specified length. The resulting substring is stored in the string variable “strtwo.” Finally, the program displays the extracted substring, which is stored in the variable “strtwo,” as the output on the screen.
Example #2C++ program to demonstrate substr function that returns the substring extracted from the given string starting from the specified position up to the number of characters from the starting position specified as length:
Code:
using namespace std; int main() { string strone = " EDUCBA is the best site for learning"; string strtwo = strone.substr(0, 6); cout << "The given string is: " << strone << "n" <<endl; cout << "The substring extracted from the given string is: " << strtwo << "n" << endl; return 0; }Output:
Example #3C++ program to demonstrate substr function that returns the substring extracted from the given string starting from the specified position up to the number of characters from the starting position specified as length:
Code:
using namespace std; int main() { string strone = " Learning is fun"; string strtwo = strone.substr(12, 3); cout << "The given string is: " << strone << "n" <<endl; cout << "The substring extracted from the given string is: " << strtwo << "n" << endl; return 0; }Output:
In the above program, we have included the headers iostream and string, allowing us to use cin, court, and substr. The program calls the main method and defines a string variable called “strone” to store the original string. The program then uses the substr function to extract a substring from the string “strone” starting from a specified position and extending for a specified length. It stores the resulting substring in the string variable “strtwo.” Finally, the program displays the extracted substring, which is stored in the variable “strtwo,” as the output on the screen.
Recommended ArticlesWe hope that this EDUCBA information on “C++ Substring” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading Working Of Substr() Function In C++
Working Of Bitwise_And() Operator In Opencv
Introduction to OpenCV bitwise_and
Whenever we are dealing with images while solving computer vision problems, there arises a necessity to wither manipulate the given image or extract parts of the given image based on the requirement, in such cases we make use of bitwise operators in OpenCV and when the elements of the arrays corresponding to the given two images must be combined bit wise, then we make use of an operator in OpenCV called but wise and operator using which the arrays corresponding to the two images can be combined resulting in merging of the two images and bit wise operation on the two images returns an image with the merging done as per the specification.
Start Your Free Software Development Course
The syntax to define bitwise_and() operator in OpenCV is as follows:
bitwise_and(source1_array, source2_array, destination_array, mask)
where source1_array is the array corresponding to the first input image on which bitwise and operation is to be performed,
source2_array is the array corresponding to the second input image on which bitwise and operation is to be performed,
destination_array is the resulting array by performing bitwise operation on the array corresponding to the first input image and the array corresponding to the second input image and
mask is the mask operation to be performed on the resulting image and it is optional.
Working of bitwise_and() Operator in OpenCVWorking of bitwise_and() operator in OpenCV is as follows:
In order to be able to perform bit wise conjunction of the two arrays corresponding to the two images in OpenCV, we make use of bitwise_and operator.
To be able to make use of bitwise_and operator in our program, we must import the module cv2.
The images whose arrays are to be combined using bitwise_and operator are read using imread() function.
Then the corresponding arrays of those images are passed to the bitwise_and operator.
The bitwise_and operator returns an array that corresponds to the resulting image from the merger of the given two images.
The operation of bitwise_and can be done on images having same dimensions only.
Examples of OpenCV bitwise_andFollowing are the examples are given below:
Example #1OpenCV program in python to demonstrate bitwise_and operator to read two images using imread() function and then merge the given two images using bitwise_and operator and then display the resulting image as the output on the screen:
Code:
#importing the modules cv2 and numpy import cv2 import numpy as np #reading the two images that are to be merged using imread() function imageread1 = cv2.imread('C:/Users/admin/Desktop/plane.jpg') imageread2 = cv2.imread('C:/Users/admin/Desktop/car.jpg') #using bitwise_and operation on the given two images resultimage = cv2.bitwise_and(imageread1, imageread2, mask = None) #displaying the merged image as the output on the screen cv2.imshow('Merged_image', resultimage) cv2.waitKey(0) cv2.destroyAllWindows()Output:
In the above program, we are importing the module cv2 and numpy. Then we are reading the two images that are to be merged using imread() function. Then we making use of bitwise_and operator by specifying the two input images as the parameters which returns the merged image as the resulting image displayed as the output on the screen. The output is shown in the snapshot above.
Example #2OpenCV program in python to demonstrate bitwise_and operator to read two images using imread() function and then merge the given two images using bitwise_and operator and then display the resulting image as the output on the screen:
#importing the modules cv2 and numpy import cv2 import numpy as np #reading the two images that are to be merged using imread() function imageread1 = cv2.imread('C:/Users/admin/Desktop/logo.png') imageread2 = cv2.imread('C:/Users/admin/Desktop/educbalogo.jpg') #using bitwise_and operation on the given two images resultimage = cv2.bitwise_and(imageread1, imageread2, mask = None) #displaying the merged image as the output on the screen cv2.imshow('Merged_image', resultimage) cv2.waitKey(0) cv2.destroyAllWindows()Output:
In the above program, we are importing the module cv2 and numpy. Then we are reading the two images that are to be merged using imread() function. Then we making use of bitwise_and operator by specifying the two input images as the parameters which returns the merged image as the resulting image displayed as the output on the screen. The output is shown in the snapshot above.
Example #3OpenCV program in python to demonstrate bitwise_and operator to read two images using imread() function and then merge the given two images using bitwise_and operator and then display the resulting image as the output on the screen:
Code:
#importing the modules cv2 and numpy import cv2 import numpy as np #reading the two images that are to be merged using imread() function imageread1 = cv2.imread('C:/Users/admin/Desktop/tree.jpg') imageread2 = cv2.imread('C:/Users/admin/Desktop/educbatree.jpg') #using bitwise_and operation on the given two images resultimage = cv2.bitwise_and(imageread1, imageread2, mask = None) #displaying the merged image as the output on the screen cv2.imshow('Merged_image', resultimage) cv2.waitKey(0) cv2.destroyAllWindows()Output:
In the above program, we are importing the module cv2 and numpy. Then we are reading the two images that are to be merged using imread() function. Then we making use of bitwise_and operator by specifying the two input images as the parameters which returns the merged image as the resulting image displayed as the output on the screen. The output is shown in the snapshot above.
Example #4OpenCV program in python to demonstrate bitwise_and operator to read two images using imread() function and then merge the given two images using bitwise_and operator and then display the resulting image as the output on the screen:
Code:
#importing the modules cv2 and numpy import cv2 import numpy as np #reading the two images that are to be merged using imread() function imageread1 = cv2.imread('C:/Users/admin/Desktop/plane1.jpg') imageread2 = cv2.imread('C:/Users/admin/Desktop/educbatree.jpg') #using bitwise_and operation on the given two images resultimage = cv2.bitwise_and(imageread1, imageread2, mask = None) #displaying the merged image as the output on the screen cv2.imshow('Merged_image', resultimage) cv2.waitKey(0) cv2.destroyAllWindows()Output:
In the above program, we are importing the module cv2 and numpy. Then we are reading the two images that are to be merged using imread() function. Then we making use of the bitwise_and operator by specifying the two input images as the parameters which returns the merged image as the resulting image displayed as the output on the screen. The output is shown in the snapshot above.
Recommended ArticlesWe hope that this EDUCBA information on “OpenCV bitwise_and” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Xlookup Function In Google Sheets
Learn more about working with Lambda Functions, Named Functions, and X-Functions in the FREE Lambda Functions 10-Day Challenge course
The XLOOKUP function in Google Sheets is a new lookup function in Google Sheets that is more powerful and flexible than the older lookup functions like VLOOKUP or HLOOKUP.
XLOOKUP matches a search key in a lookup range and returns the value from a result range at that same position. If XLOOKUP does not find a match, you can specify a default value. You can control the match mode, like other lookup functions, and even control the search mode. More on that below, but first let’s see a simple example.
Here’s a simple XLOOKUP formula that looks for the search key in column A and returns a value from column C:
=XLOOKUP(
E2
,
A2:A11
,
C2:C11
)
It looks like this in the Sheet:
🔗 Get this example and others in the template at the bottom of this article.
XLOOKUP Function Syntax=XLOOKUP(search_key, lookup_range, result_range, [missing_value], [match_mode], [search_mode])
It takes a minimum of three and a maximum of six arguments:
search_key
The value you want to search for.
lookup_range
The range to search. It must be either a single column or a single row.
result_range
The range to consider for the result. The return value is taken from the position of the matched value in the lookup array if the search key is found. The result range must match the dimensions of the lookup range.
[missing_value]
The fallback value to return if no match exists. This is an optional argument and if it is omitted, an error is returned if no match exists.
[match_mode]
This optional argument lets you specify what match mode to use. If unspecified, an exact match is used.
The options are:
Option Match Mode Behavior
0 Exact match search
1 Exact match or next value that is bigger than the search key
-1 Exact match or next value that is lower than the search key
2 Wildcard match
[search_mode]
The different search options are:
Option Search Mode Behavior
1
-1
2 Search through the range using binary search and assuming the range is sorted in ascending order
-2 Search through the range using binary search and assuming the range is sorted in descending order
XLOOKUP Function Notes
The lookup range can only be either a single row or a single column. It cannot be an array with multiple rows and columns.
The result range must be compatible with the size of the lookup range. For example, if the lookup range is a column of data with 10 rows and 1 column, then the result range must also have 10 rows (though it can have more than 1 column).
XLOOKUP Function ExamplesLet’s see some more examples of the XLOOKUP function in Google Sheets.
Example 1: Basic Exact MatchIf you omit the optional match mode argument, the XLOOKUP function will perform an exact match.
I.e. when you write it with only the first three arguments, a search key, a lookup range, and a result range, then it will look for an exact match. We saw this in the example at the top of this page:
=XLOOKUP(
E2
,
A2:A11
,
C2:C11
)
Which works like this in the Sheet:
Example 2: Missing ValueNow, we can specify a fallback value if no match is found. This is done with the fourth (optional) argument, e.g.
=XLOOKUP(
E2
,
A2:A11
,
C2:C11
,
"No match"
)
In our Sheet:
In this case, the search key “XYZ123” is not found in the lookup array (column A) so the XLOOKUP function returns the fallback missing value, which we set to “No match”.
Example 3: XLOOKUP Function LeftAnother benefit with the XLOOKUP function is that the lookup range does not have to be to the left of the result range, which is the case with the VLOOKUP (though there is a complicated workaround with array literals).
The formula does not change, but this time the result range is positioned to the left of our lookup range:
=XLOOKUP(
E2
,
C2:C11
,
B2:B11
,
"No match"
)
As you can see, it works equally well in our Sheet:
Example 4: Approximate MatchThe fifth argument of the XLOOKUP function determines the matching mode. If it is omitted or set to 0, then an exact match is performed.
However, there are situations where the approximate matching option works really well.
Consider the case when our search key falls between two values in the lookup range. It’s not an exact match, but we might still want to return a result to say that it’s lower than X, or higher than Y.
For example, consider this bank savings scenario:
The XLOOKUP formula for this example is:
=XLOOKUP(
B8
,
B2:B5
,
C2:C5
,,
-1
)
Notice the -1 as the final argument, which tells the function to look for an exact match and if it doesn’t find one, to return the value that is lower in the array.
In this example, it doesn’t find the $137,832 exactly, so it looks at the lower value in the array, i.e. $100,000. This is in position 3 of the lookup array, so it returns the value from the 3rd position of the results array, i.e. 1.25%.
One final thing to mention with this example, notice how the fourth argument is blank. This is where we can specify a “missing value” for when no match is found. However, it’s not required here because we’re using an approximate match anyway.
Example 5: Wildcard MatchXLOOKUP in Google Sheets supports three wildcards, *, ?, and ~.
The star * matches zero or more characters.
The question mark ? matches exactly one character.
The tilde ~ is an escape character that lets you search for a * or ?, instead of using them as wildcards.
Let’s see an example that uses a surname to find the full name:
=XLOOKUP(
"*"
&
B15
,
A2:A11
,
A2:A11
,
"No match"
,
2
)
And another example that uses a surname to return transaction revenue from that row:
=XLOOKUP(
"*"
&
B15
,
A2:A11
,
D2:D11
,
"No match"
,
2
)
Both formulas are seen in the following image, with the first one in cell B17 and the second in cell B18:
There are two important things to notice with this formula:
1) The search key is “Peterson”, but to use it in the XLOOKUP function, we first add the wildcard star character that matches anything before the “Peterson”:
I.e. *Peterson
Note, if there were multiple “Peterson” in this dataset this could cause an issue. In this case, you might want to try using the QUERY function or the FILTER function to return all the “Peterson” results.
2) The match mode in the fifth argument is set to 2, which indicates that this is a wildcard search.
Example 6: Return Multiple ResultsThe XLOOKUP function can return multiple results for a single match, not just a single result like a VLOOKUP (although there is a workaround for VLOOKUP to return multiple columns).
XLOOKUP returns multiple results by specifying a result range with multiple columns (or rows if you’re doing a horizontal lookup).
The formula is:
=XLOOKUP(
B13
,
A2:A11
,
B2:E11
)
This gives the result:
Example 7: Different Search ModeThe final argument lets you change the search method used. The default is to search from top to bottom of your range, but you can change this to search from the bottom to the top if that makes sense.
The XLOOKUP can also perform super quick binary searches, but this requires your data to be sorted correctly to avoid incorrect results.
XLOOKUP Function TemplateIf you can’t access the template, it might be because of your organization’s Google Workspace settings.
It’s part of the Lookup family of functions in Google Sheets. You can read about it in the Google Documentation.
Can C And C++ Topple Python And Java In The Coming Years?
In the list of top programming languages on GitHub, C and C++ have climbed up the rankings
The most frequently used programming languages in GitHub projects are JavaScript, Python and Java, TypeScript, and C and C++, according to GitHub’s 2023 Octoverse report. The list of the top programming languages on Microsoft-owned GitHub was stable this year, with no difference in the line-up except for PHP which dropped.
The three programming languages on the list were Shell, C, and Ruby. Hashicorp Configuration Language (HCL) — increased by 56%, and Rust which increased by over 50% was the most popular programming language with the strongest growth rate. TypeScript expanded by 37.8%. Additionally, Lua, Go, Shell, Makefile, C, Kotlin, and Python saw substantial growth. The programming languages C and C++ topple Python and Java in the list. GitHub attributes Go’s expansion into cloud development projects like Docker and Kubernetes was supported by Google. Google prefers Kotlin for Android development over Java, which is evidence of Android’s influence on mobile app development.
However, it should be noted that Java did not see substantial growth on GitHub. However, it continues to rank among the top three languages on GitHub and Tiobe.
With 19,800 contributors, Microsoft’s cross-platform code editor VS Code took the top spot among open-source projects. Home Assistant, an open-source home automation kit managed by Paulus Schoutsen, came in second with 13,500 contributors.
With 12,400 contributions, Google’s Flutter UI framework came in third place. Other significant initiatives were Google’s Material UI, Microsoft’s Azure Docs, Verbal’s chúng tôi TypeScript, Google’s Material UI, and the TensorFlow machine-learning framework.
94 million developers currently use the GitHub platform to store code, submit pull requests, and make contributions. By adding 20.5 million new members in the most recent year, the community expanded 27% year over year. According to the corporation, GitHub is used by 90% of Fortune 100 organizations, and 90% of businesses employ open-source software. Additionally, to coordinate their OSS plans, 30% of Fortune 100 corporations have established an open-source program office (OSPO).
85.7 million new repositories were hosted by GitHub in 2023, an increase of 20%. A staggering 3.5 contributions to open-source projects were also made on GitHub. Commits, problems, pull requests, debates, visits, pushes, and pull requests are a few examples of these contributions.
Additionally, GitHub noted an increase in private repositories. In 2023, just 20% of all contributions made on GitHub went to open-source projects. In 2023, GitHub made private repositories available to GitHub Free users.
Additionally, it looks that GitHub’s Dependabot and Advisory Database are improving security, particularly in patching weak dependencies. Updates to dependencies increased from 16 million in 2023 to 24 million in 2023. There were 13 million secured projects in 2023 and 18 million in 2023.
According to the most current popularity rankings from developer analyst RedMonk, developers who learn JavaScript, Python, Java, and PHP appear to be quite safe in their choice of programming languages for the time being.
Since RedMonk’s initial biannual rating in March, neither the list’s top four languages’ positions nor their composition has changed. Additionally, there hasn’t been much of a shift in the top 20 rankings, which are determined by the quantity of GitHub projects and the amount of StackOverflow developer forum conversations.
The top four languages—Python, Java, C, and C++—have likewise solidified their positions, according to Tiobe Software, which publishes a monthly language index, leaving little opportunity for the competition from newcomers.
C++ Program To Sort The Elements Of An Array In Descending Order
Arranging data items in a proper form is an essential task while solving some problems in an efficient way. The element sorting problem is one of the most commonly discussed arranging problem. In this article we will see how to arrange the array elements in descending order (decreasing order of their values) in C++.
There are many different sorting algorithms present in this domain to sort numeric or nonnumeric elements in a given order. In this article we will see only two simple methods of sorting. The bubble sort and the selection sort. Let us see them one by one with proper algorithms and C++ implementation code.
Sort array in descending order using bubble sorting techniqueThe bubble sorting technique is one of the most common and easier method for sorting elements in an array. This method checks two consecutive elements, if they are in correct order, then skip to the next elements, otherwise interchange them to place them in correct order. Then move towards right and do the same for the other pair of values. The bubble sorting technique has few phases, at the end of each phase, one element is being placed at the correct intended position. Let us see the algorithm for bubble sorting technique.
Algorithm
read array A and its size n as input
for i ranging from 0 to n-1, do
for j ranging from 0 to n – 2, do
if A[j] < A[j + 1], then
swap A[j] and A[j + 1]
end if
end for
end for
Exampleusing namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << “, “; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } void solve( int arr[], int n ){ int i, j; for ( i = 0; i < n; i++ ) { for ( j = 0; j < n-1; j++ ) { if ( arr[j] < arr[ j+1 ] ) { swap( arr[j], arr[ j + 1 ] ); } } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << “Array before sorting: “; display(arr, n); solve( arr, n ); cout << “nArray After sorting: “; display(arr, n); }
Output Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2, Sort array in descending order using selection sorting techniqueIn the selection sorting technique, we find either minimum element or the maximum element from the given array starting from index i to the end of this array. Assume we are finding maximum element. In each phase, it finds the minimum from index i to end, then place the element at its desired position then again search for next maximum element from the index i + 1 and so on. After completing these phases, the entire array will be sorted accordingly.
Algorithm
read array A and its size n as input
for i ranging from 0 to n-1, do
ind := index of maximum element of A starting from i to n
if A[ i ] < A[ ind ], then
swap A[ i ] and A[ ind ]
end if
end for
Exampleusing namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << “, “; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } int max_index( int arr[], int n, int s, int e ){ int max = 0, max_ind = 0; for ( int i = s; i < e; i++ ) { max = arr[i]; max_ind = i; } } return max_ind; } void solve( int arr[], int n ){ int i, j, ind; for ( i = 0; i < n; i++ ) { ind = max_index( arr, n, i, n ); if ( arr[i] < arr[ ind ] ) { swap( arr[i], arr[ ind ] ); } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12,89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << “Array before sorting: “; display(arr, n); solve( arr, n ); cout << “nArray After sorting: “; display(arr, n); }
Output Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2, ConclusionSorting problem is a fundamental problem where we arrange the numbers or other values in a given arrangement logics. There are many different sorting techniques available in this domain, however, in this article we have seen two sorting techniques which are easy to implement and easy to understand. These two methods are bubble sort technique and the selection sorting technique. Using these two methods, we have sorted the set of data in descending (non-increasing) order. These two sorting methods are not much efficient in respect of time, but they are simple to understand. Both of these two methods take O(n2) amount of time, where n is the size of input. The bubble sort can be made faster by a simple checking whether when there is no swap in any phase, the next consecutive phase will not change anything.
C++ Program To Find The Gcds Of Given Index Ranges In An Array
In the field of data structure, a range query is a pre-processing method to operate on some input data in an efficient manner. A range query is responsible to answer any query of the particular input on any data subset. If we want to copy some data columns from a table we need to maintain an index for that particular dataset. An index is a direct link or a key, which is designed to provide an efficient searching process in a data set. It is mainly used to speed up the data retrieving from a lost data source.
In mathematics, Greatest Common Divisor aka GCD is a largest possible integer which can divide both of the integers present as the input. Here, all numbers must be present with a non-zero value. Just take an example:
GCD of 70, 80 = 10 (10 is the largest number which divides them with remainder as 0) GCD of 42, 120, 285 = 3 (3 is the largest number which divides them with remainder as 0) Algorithm to find the GCDs of given index ranges in an array (in Detailed)
Step 1 − Start
Step 2 − Construct a section of arr[0] to arr[n-1]
Step 3 − Continue the equal partition
Step 4 − Recursive call for these two parts
Step 5 − For each, save only the greatest common divisor value will save in a segment tree
Step 6 − Build another segment tree to fill it from bottom to top
Step 7 − Each node stores some data of GCD with a certain range
Step 8 − If the node range is startQuery and endQuery, then return a value node
Step 9 − Else if, the range is invalid, it will return a null or -1 as output
Step 10 − Else, return a GCD function as a recursive call
Step 11 − Terminate
Algorithm to find the GCDs of given index ranges in an array (in Short)
Step 1 − Assume, a and b are the two non-zero integers
Step 2 − Let, a mod b = R
Step 3 − If, a=b and b=R
Step 4 − Then, repeat step 2 and step 3
Step 5 − Process will run until a mod b become greater than zero
Step 6 − GCD = b
Step 7 − Terminate
Syntax to find the GCDs of given index ranges in an array Begin if c = 0 OR d = 0, then return 0 if c = d, then return b return findGCD(c-d, d) else return findGCD(c, d-c) EndHere in this syntax we can see the possible logic code, how to find the Greatest Common Divisor of two non-zero digits. The time complexity for the process is O(Q*N*log(Ai)) and the auxiliary space is evaluated as O(1).
Approach to follow:-
Approach 1 − Program to find GCD of a number in a given Range using segment Trees
Program to find GCD of a number in a given Range using segment TreesTo find GCD of a number in a given Range using segment Trees, we need to follow some unavoidable steps.
Construction of a segment tree:
The elements of an input array are the leaf nodes.
Each individual internal node represents the GCD of all leaf nodes.
Array representation can be done by a segment tree.
-2*(i+1), index’s left element
-2*(i+2), index’s right element
-Parent is floor((i-1)/2)
Construction of a new segment tree by using the given array:
Begin the process with a segment arr[0 . . . n-1].
Divide them into two halves.
Call same for the both halves.
Store the value of GCD.
Construction of given range for GCD:
For every possible query, move the halves of thee tree present left and right.
When the given range overlaps on a half; return the node.
When it lies outside the given range, return 0 at that moment.
For partial overlapping, traverse and get return according the method follows.
Exampleusing namespace std; int* st; int findGcd(int ss, int se, int qs, int qe, int si) { return 0; return st[si]; int mid = ss + (se – ss) / 2; return __gcd(findGcd(ss, mid, qs, qe, si * 2 + 1), findGcd(mid + 1, se, qs, qe, si * 2 + 2)); } int findRangeGcd(int ss, int se, int arr[], int n) { cout << “Invalid Arguments” << “n”; return -1; } return findGcd(0, n – 1, ss, se, 0); } int constructST(int arr[], int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return st[si]; } int mid = ss + (se – ss) / 2; st[si] = __gcd(constructST(arr, ss, mid, si * 2 + 1), constructST(arr, mid + 1, se, si * 2 + 2)); return st[si]; } int* constructSegmentTree(int arr[], int n) { int height = (int)(ceil(log2(n))); int size = 2 * (int)pow(2, height) – 1; st = new int[size]; constructST(arr, 0, n – 1, 0); return st; } int main() { int a[] = { 20, 30, 60, 90, 50 }; int n = sizeof(a) / sizeof(a[0]); constructSegmentTree(a, n); int l = 1; int r = 3; cout << “GCD of the given range is here. Please collect your data:”; cout << findRangeGcd(l, r, a, n) << “n”;
return 0; }
Output GCD of the given range is here. Please collect your data:30 ConclusionIn this article thus, we have developed some possible code by using the particular programming environment. With these encoded logic and the mentioned algorithm we have learned how to find out the GCDs of given index ranges in an array properly.
Update the detailed information about Working Of Substr() Function In C++ on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!