![]() |
VOOZH | about |
Given a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n.
Examples:
Input : n = 4
Output : 7
Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4
Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4)
= 1 + 1 + 1 + 1 + 2 + 1
= 7
Input : n = 12
Output : 105
Input : n = 1
Output : 0
Input : n = 2
Output : 1
A Naive approach is to run two loops one inside the other. Select all pairs one by one, find GCD of every pair and then find sum of these GCDs.
The idea is to use Euler's Totient function Φ(n) for an input n is count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively prime to 4, 2 numbers smaller or equal to 3 that are relatively prime to 3. And 4 numbers smaller than or equal to 5 that are relatively prime to 5.
The idea is to convert given problem into sum of Euler Totient Functions.
Sum of all GCDs where j is a part of pair is and j is greater element in pair:
Our final result is
The above equation can be written as :For every possible GCD 'g' of j. Here count(g) represents count of pairs having GCD equals to g. For every such pair(i, j), we can write : gcd(i/g, j/g) = 1
We can re-write our previous equation as
Sumj = ∑d * ϕ(j/d)
For every divisor d of j and phi[] is Euler Totient number
Example : j = 12 and d = 3 is one of divisor of j so in order to calculate the sum of count of all pairs having 3 as gcd we can simple write it as
=> 3*ϕ[12/3]
=> 3*ϕ[4]
=> 3*2
=> 6
Therefore sum of GCDs of all pairs where 12 is greater part of pair and 3 is GCD.
GCD(3, 12) + GCD(9, 12) = 6.
Complete Example :
N = 4
Sum1 = 0
Sum2 = 1 [GCD(1, 2)]
Sum3 = 2 [GCD(1, 3) + GCD(2, 3)]
Sum4 = 4 [GCD(1, 4) + GCD(3, 4) + GCD(2, 4)]
Result = Sum1 + Sum2 + Sum3 + Sum4
= 0 + 1 + 2 + 4
= 7
Below is the implementation of above idea. We pre-compute Euler Totient Functions and result for all numbers till a maximum value. The idea used in implementation is based this post.
Summation of 4 = 7 Summation of 12 = 105 Summation of 5000 = 61567426
Time complexity: O(MAX*log(log MAX))
Auxiliary space: O(MAX)