Total number of common factors for two numbers LARGE VALUES up to 10^12 Inputs are two values \$1 \le m , n \le 10^{12}\$. I don't know why my code is taking so long for large values where the time limit is 1 sec. Please suggest some critical modifications.

#include &lt;iostream&gt;
#include&lt;algorithm&gt;
using namespace std;

int main() {
    long long count = 0, m, n;
    cin &gt;&gt; m &gt;&gt; n;

    for (long long int i = 1; i &lt;= ((min(m, n)) / 2) + 1; i++) {
        if ((m%i == 0) &amp;&amp; (n%i == 0)) {
            count++;
        }
    }

    if (((n%m == 0) || (m%n == 0)) &amp;&amp; (n != m)) {
        count++;
    }

    cout&lt;&lt;count;

    return 0;
}
long long count = 0, m, n;
    ...
    for (long long int i = 1; i &lt;= ((min(m, n)) / 2) + 1; i++) {


long long or long long int? I'm not a C++ programmer so I don't know whether style guides have a preference, but I'm quite certain that you should be consistent.




  Inputs are two values \$1 \le m , n \le 10^{12}\$. I don't know why my code is taking so long
  ...

   for (long long int i = 1; i &lt;= ((min(m, n)) / 2) + 1; i++) {



There you go. The main loop runs up to \$5 \times 10^{11}\$ times. As a rule of thumb, when brute-forcing a problem I work on the basis that \$10^9\$ is about as high as I want to go.

Solution: change your algorithm. This will require learning some mathematics, and I'm not going to write a detailed tutorial, but there are two things you need:


Basic number theory: unique prime factorisation, greatest common divisor, finding it efficiently;
Sane factorisation of a small number (and \$10^{12}\$ is very small in these terms)


If you wanted to do it properly then you could extend the number theory research and learn about Euler's totient function.