Let's fix (for example j = 12) and find the number of such that i = GCD(i, 12).
The values of that satisfy this equation are i = 1, 2, 3, 4, 6, 12. So, any that is a divisor of satisfies the equation i = GCD(i, 12).
The number of such for which i = GCD(i, j) is equal to the number of divisors of . Since 1 \le j \le n, we need to find the count of all divisors of numbers from to . In other words, we need to find the sum
However, calculating requires factoring the number , so direct computation of this sum takes time.
Let's look at the sum of divisors in a different way. Among the divisors of numbers from to , one appears \lfloor{n \over 1}\rfloor times, two appears \lfloor{n \over 2}\rfloor times, and so on (the divisor appears \lfloor{n \over i}\rfloor times). The number of required pairs of integers is
This sum can be computed in time.
Example
For n = 6 we have the next pairs:
The number of pairs is
Algorithm implementation
Read the value of .
scanf("%d",&n);Compute the answer using the formula and print it.
s = 0;
for (i = 1; i <= n; i++)
s += n / i;
printf("%d\n",s);Java implementation
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int s = 0;
for(int i = 1; i <= n; i++)
s += n / i;
System.out.println(s);
con.close();
}
}Python implementation
Read the value of .
n = int(input())Compute the answer using the formula and print it.
s = 0
for i in range(1,n+1):
s += n // i
print(s)