![]() |
VOOZH | about |
Given an integer N, the task is to find a sequence of distinct integers whose Harmonic Mean is N itself. In case such a sequence doesn't exist, print -1.
Examples:
Input: N = 5
Output: {3, 4, 5, 6, 20}
Explanation: Given sequence is the correct answer because 5/(1/3+1/4+1/5+1/6+1/20)=5. Note that there are other possible sequences as well. For example - {2, 6, 12, 20, 5}.Input: N=3
Output: {2, 3, 6}
Approach: To solve the problem follow the below observations:
Observations:
- For N = 1, the sequence {1} satisfies the conditions.
- For N = 2, there is no possible sequence satisfying the given conditions. So, we'll consider the case for N > 2.
- We know that 1/X(X+1) = 1/X - 1/(X+1). Using this fact, we can see that the sequence {1*2, 2*3, ..., (N-1)*N, N} would satisfy the required conditions. (Reason: {1*2, 2*3, ..., (N-1)*N, N} = {2, 6, 12, 20.....(N-1)*N, N}.
- The harmonic mean of this sequence:
- N/(1/(1*2) + 1/(2*3) + 1/(3*4) +...+ 1/(N-1)*N) + 1/N)
- N/(1-1/2 + 1/2-1/3 + 1/3-1/4) +...+ 1/(N-1)-1/N + 1/N)
- N/1 = N
- However, for the cases when N can be represented as N=X*(X-1), for some integer X, it can be seen that the above observation fails as the sequence would contain a duplicate.
For example, for N=6 (6=2*3), the sequence would be {2, 6, 12, 20, 30, 6}. Here 6 is repeated, but we want all distinct integers in the sequence.
- Suppose the sequence from observation 1 is {A1, A2, A3....AN}. To avoid repeating numbers when N is even (as N = X*(X-1) will be possible only when N is even), we'll print the sequence {2, 2*A1, 2*A2,....,2*A(N-2), 2*(N-1)}.
The following steps can be used to solve the problem :
Following is the code based on the above approach:
2 6 12 20 5
Time Complexity: O(N)
Auxiliary Space: O(1)