Table of Contents
algorithm
grammar
max() function syntax
method
Example
Output
in conclusion
Home Backend Development C++ Find the greatest common divisor in a given range

Find the greatest common divisor in a given range

Aug 28, 2023 pm 02:28 PM
range greatest common divisor

Find the greatest common divisor in a given range

The question states that we need to find the GCD within a given range. We will get two positive integers x and y and two integers p and q in the range [p,q]. We need to find the GCD (greatest common divisor) of the numbers x and y that fall in the range [p,q]. GCD, known in mathematics as the greatest common divisor, is the largest positive integer that divides two given positive integers. The given integer must not be zero. For any two positive integers x and y, it is expressed as gcd(x,y).

For example, we have two positive integers 6 and 9. The greatest common divisor gcd(6,9) will be 3 because it is the largest number that divides these two numbers.

But in this problem, we need to find the greatest common divisor of two given positive integers within a specified range. Let us understand this problem through an example. We will be given 4 numbers as input x and y to find the gcd of these numbers and two numbers indicating the range of gcd i.e. [p,q].

Input: x=8, y=12, p=1, q=3

Output: 2

Explanation - Since the greatest common divisor of the given two numbers x and y is 4. But 4 is not in the range [1,3]. The greatest common divisor in the range [1,3] is 2, which is our desired output.

Input: x=17, y=15, a=5, b=10

Output:-1

Explanation - The greatest common divisor of the numbers 17 and 15 is 1. Because 1 is not in the given range [5,10]. When there is no common divisor in the given range, we need to print -1 as output.

algorithm

The algorithm we use to solve the problem is very simple and mathematically related. First, we will find the gcd (greatest common divisor) of the numbers x and y. In C, there is a built-in function called gcd() which returns the greatest common divisor of numbers as output.

grammar

int divisor=gcd(x,y);
Copy after login

We can also use the efficient method of Euclidean's algorithm to find the gcd of two numbers. Both work at the same time, and the time complexity is O(log(min(x,y)).

Now, we can use simple laws of arithmetic to conclude that the number divided by the gcd of two numbers will also be divided by the two numbers themselves . So, iterating from i=1 to sqrt(gcd(x,y)) in a for loop will help us get all the common divisors of the number.

Then, check if each i up to sqrt(gcd(x,y)) i divides gcd(x,y). If i divides gcd(x,y), then we can say that gcd(x,y)/i will also be the divisor of gcd, thus concluding that it is also the common divisor of the numbers x and y.

Let us understand this concept through an example. Suppose x and y are 32 and 48 respectively. gcd(18,27) is 16. So in this case, we will iterate from i=1 to i<=4, which is sqrt(16). Let us consider i=2. Here I divide by gcd(18,27), which is 16/2, which equals 8. So gcd(x,y)/i also divides gcd(x,y) to get i. <=4,即 sqrt(16)。让我们考虑 i=2。这里我除以 gcd(18,27),即 16/2,等于 8。因此 gcd(x,y)/i 也会除 gcd(x,y) 得到 i。

Note - If the number n divided by any number x gives y, which can be expressed as $\frac{n}{x}\:=\:y$ then y will divide n by x $ (x\:\times\:y\:=\:n)$.

This algorithm may be the most effective way to solve this problem. While following this algorithm, we will constantly check if the common denominator is in the range [a,b]. If not, we will use the max() function to continuously update the divisor in the variable to get the greatest common divisor in the range.

max() function syntax

int m = max(a,b);
Copy after login

It returns the maximum value of a and b.

method

Here is the approach we will follow -

  • Initialize a function to calculate the greatest common divisor within a given range.

  • Calculate the gcd of two given positive numbers x and y.

  • Initialization variable name ans = -1.

  • Iterate from i=1 to i<=sqrt(gcd(x,y)) in the for loop and constantly check whether i divides gcd(x,y). <=sqrt(gcd(x,y)) 并不断检查 i 是否整除 gcd(x,y)。

  • If (gcd(x,y)%i)=0, check whether i is in the range [a,b] and whether to use the max() function to store it in ans so that we can get the maximum The common denominator lies within this range.

  • Also check whether gcd/i is within the range. If it is within the range, use the max() function again to update the value of ans.

  • Return ans after completing all iterations in the for loop.

Example

Implementation of this method in C -

#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;

// to calculate gcd of two numbers using Euclidean algorithm
int gcd(int a, int b){
   if(a == 0)
   return b;
   return gcd(b % a, a);
}

//function to calculate greatest common divisor in the given range [a,b]
int build(int x, int y, int a, int b) {

   //using C++ inbuilt library to calculate gcd of given numbers
   int z = gcd(x, y); //we can use euclidean algorithm too as an alternative
   int ans = -1; //storing -1 for the case when no common divisor lies in the range
   for(int i = 1; i<=sqrt(z); i++) { //iterating until sqrt(z) because either of two factors
      //of a number must be less than square root of the number
      if(z % i == 0) {
         if(i >= a && i <= b) //checking it i lies in the range
         ans = max(ans, i); //storing maximum value
         if((z / i) >= a && (z / i) <= b)
         ans = max(ans, z / i);
      }
   }
   return ans;
}
int main() {
   int x, y, a, b;
   x=24, y=42, a=3, b=9;
   cout << build(x, y, a, b) <<" is the gcd that lies in range ["<<a<<","<<b<<"]"<<endl;
   return 0;
}
Copy after login

Output

6 is the gcd that lies in range [3,9]
Copy after login

Time complexity: O(log(min(x,y)) sqrt(z)), where z is the greatest common divisor of two numbers x and y.

Space complexity: O(1), because no additional space is used.

in conclusion

We discussed ways to solve the gcd problem for two numbers in the range [a,b]. This is how we can solve the above problem in C using various different functions.

I hope you found this article helpful and clarified all your concepts related to this problem.

The above is the detailed content of Find the greatest common divisor in a given range. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

See all articles