Processing math: 100%

Monday, 3 January 2022

Same GCD?

Find the number of x that satisfies gcd(a,m)=gcd(a+x,m) where 0<=x<m. For example, if a=4 and m=9, there would be 6 x which are 0,1,3,4,6,7.

From Euclidean algorithm, we know that gcd(a,b)=gcd(amodb,b). For example, if a=4 and b=8, we know that gcd(12,8)=gcd(12mod8,8), in this case, which is 4. Back to our question, we know that 0<=x<m, which means that the range of a+x would be a..m+a, it can be divided by m. Let k be (a+x)modm, the range of k is 0..m. Now we can rewrite it to gcd(a,m)=gcd(k,m).

Let's say gcd(a,m)=gcd(k,m)=g, it then can be rewritten as gcd(kg,mg)=1. In this case, we can use Euler's totient function to find out how many numbers from 1 to kg are co-prime to kg. The function is defined as

φ(n)=nn=p|n(11p)

For example, for φ(36), it can be factoralized as φ(2232) = 36(112)(113)=12. Those 12 numbers are 1,5,7,11,13,17,19,23,25,29,31 and 35.

Here's the implementation of Euler's totient function in C++.

long long phi(long long n) {
    long long result = n;
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            while (n % i == 0)
                n /= i;
            result -= result / i;
        }
    }
    if (n > 1)
        result -= result / n;
    return result;
}

Therefore, back to our question, the solution is relatively simple.

long long a, m; cin >> a >> m;
cout << phi(m / gcd(a, m)) << endl;

No comments:

Post a Comment

A Fun Problem - Math

# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...