You are given an integer ‘N’ , calculate and print the sum of :
LCM(1,N) + LCM(2,N) + .. + LCM(N,N)
where LCM(i,n) denotes the Least Common Multiple of the integers ‘i’ and ‘N’.
The first line of input contains a single integer T representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the number of times we have to take LCM sum.
Output Format :
For each test case, return the required sum in a new line
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^4
Where ‘T’ is the number of test cases, and ‘N’ is the given integer
Time Limit:1sec
2
5
2
55
4
For test case 1 :
LCM(1,5) + LCM(2,5) + LCM(3,5) + LCM(4,5) + LCM(5,5) = 5 + 10 + 15 + 20 + 5 = 55
For test case 2 :
LCM(1,2) + LCM(2,2) = 2 + 2 = 4
2
1
3
1
12
can you write a code to find the LCM of two numbers ?
Using the mathematical formula, A*B = LCM(A,B) * GCD(A,B) where ‘A’ and ‘B’ are the two integers, and GCD(A,B) denotes the Greatest common divisor of ‘A’ and ‘B’.
For example, suppose
A = 20 and B = 30
Factors of A = {1,2,4,5,10,20}
Factors of B = {1,2,3,5,6,10,15,30}
The greatest common factor is 10, hence GCD(20,30) = 10.
So LCM(A,B) = A*B / GCD(A,B)
All we need to find is a GCD of two numbers.
We can find it in 2 different ways
Euclidean algorithm for finding GCD(A,B) is as follows :
A = 30, B = 20
GCD(30,20) ---> GCD(20,30%20) ---> GCD(20,10)
GCD(20,10) ---> GCD(10,20%10) ---> GCD(10,10)
GCD(10,10) ---> GCD(10,10%10) ---> GCD(10,0)
As soon as one integer becomes 0, we will stop and GCD = 10.
O(N*logN)
where ‘N’ is the number of times we have to find LCM.
We are finding GCD for each number, and for finding GCD the complexity is LogN because we repeatedly divide an integer until it becomes zero, maximum operation will be the number of digits in that integer, which are roughly logN.
O(1) since no extra space has been used.