Finding numbers with given gcd and lcm I am solving a question in which we are given the LCM and HCF and two numbers 'a' and 'b', our task is to find the pairs of numbers between a and b [inclusive] whose HCF is the given HCF and LCM is the given LCM 

I have written a code with time complexity O(m) where m is the number of integers lying between the range a and b, But on submission i am getting time limit exceeded error

IMO this is the best we can do , can we do better?
Here is the code

  #include&lt;bits/stdc++.h&gt;
  using namespace std;

  //function for calculatin gcd
  int gcd( int a,int b){
  int h;
   for(h = a&lt;b?a:b; h &gt;= 1; h--){
    if((a%h == 0) &amp;&amp; (b%h == 0))
     break;
   }

   return h;
   }

  int main(){
  int n1,n2,lcm,hcf,cnt = 0;
  cin&gt;&gt;n1&gt;&gt;n2&gt;&gt;hcf&gt;&gt;lcm;//The numbers a,b and hcf and lcm
   for(int i = n1; i &lt;= n2;i++){
   //checking if the number divides the lcm completely  
   if(lcm%i == 0){
    int a = lcm/i;// its other multiplier
    int b = gcd(a,i);//finding their gcd
        //checking if their gcd is equal to given hcf
        if(b == hcf){
         int c = (i*a)/b;//finding the lcm by a*b = lcm*hcf formula and 
                         //checking
          if(c == lcm){
           cnt++;
          }
         }
        }
       }

   cout&lt;&lt;cnt&lt;&lt;endl;
   return 0;
   }
Headers

Use the standard headers, not #include&lt;bits/stdc++.h&gt;. This is intended solely for gcc's internal use, and gratuitously renders your code completely non-portable.

Oh No! Not using namespace std;!

Please don't use using namespace std; It can, will, and does declare an unknown and almost unbounded set of names, many of which 1) you may not know about (it grows constantly), and 2) many of which are really common names that can collide with all sorts of reasonable code, leading to no end of potential problems.

Use the Library

If you're using a current compiler, you probably have std::gcd defined in &lt;numeric&gt;, so you probably don't need to define your own.

Improved Algorithm

To fit the criteria, each number you try must be a multiple of the given gcd (otherwise that wouldn't be the gcd of the number in question). As such, you can start from the smallest number that's a multiple of the gcd, but greater than your lower bound.

For example, if you're given a gcd of 21 and a lower bound of 30, you can quickly find that your starting point is 42, because that's the next number larger than 30 that's also a multiple of 21.

From there, you have to multiply each candidate by numbers that are coprime with each other--if the multipliers weren't coprime, then the common factors would become part of the gcd, and the gcd of the two would no longer be what you were given. So, for example, given a gcd of 21, you could try 21*2 = 42 with 21*3 = 63. Since 2 and 3 are coprime, that would gcd(42,63) would still be 21 (as required).