Consider all numbers from 1 to ‘N’, your task is to find the sum of gcd of all pairs (i, j) such that 1 <= i < j <= N.
For example for N = 3, all pairs are { (1, 2), (1, 3), (2, 3) }.
Note :
Gcd of two numbers (X, Y) is defined as the largest integer that divides both ‘X’ and ‘Y’.
Input Format :
The first line contains an integer 'T' which denotes the number of test cases to be run. The 'T' test cases follow.
The first line of each test case contains an integer ‘N’ representing the given integer.
Output Format :
For each test case, print an integer representing the sum of gcd of all pairs of numbers from 1 to ‘N’.
The output of each test case will be printed in a separate line.
Note :
You do not need to input or print anything, and it has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 5
1 <= 'N' <= 5000
Time Limit: 1sec
2
3
5
3
11
Test case 1:
gcd(1, 2) + gcd(1, 3) + gcd(2, 3) = 1 + 1 + 1 = 3.
Test case 2:
gcd(1, 2) + gcd(1, 3) + gcd(1, 4) + gcd(1, 5) +
gcd(2, 3) + gcd(2, 4) + gcd(2, 5) +
gcd(3, 4) + gcd(3, 5) +
gcd(4, 5) = 11.
1
1
0
Test case 1:
As there is no possible Paris, so the gcd sum is 0.
Try to extract all the pairs and find out their gcd.
For a given ‘N’, we can iterate over all possible pairs and find the resulting sum by adding them.
O((N ^ 2) * log(N)) where ‘N’ is the given integer.
As there are total (N * (N - 1) / 2) pairs and we are iterating over each pair that takes O(N ^ 2) time, also for each pair we are calculating gcd which takes O(log(N)) time in the worst case. Hence the overall time complexity is O(N ^ 2) * O (log(N)) = O((N ^ 2) * log(N)).
O(1)
As we are not using any extra space.