Given an integer n, print m increasing numbers such that the sum of m numbers is equal to n and the GCD of m numbers is maximum among all series possible. If no series is possible then print “-1”.
Input : n = 24, m = 3 Output : 4 8 12 Explanation : (3, 6, 15) is also a series of m numbers which sums to N, but gcd = 3 (4, 8, 12) has gcd = 4 which is the maximum possible. Input : n = 6 m = 4 Output : -1 Explanation: It is not possible as the least GCD sequence will be 1+2+3+4 which is greater then n, hence print -1.
The most common observation is that the gcd of the series will always be a divisor of n. The maximum gcd possible (say b) will be n/sum, where sum is the sum of 1+2+..m.
If b turns out to be 0, then the sum of 1+2+3..+k exceeds n which is invalid, hence output “-1”.
Traverse to find out all the divisors possible, a loop till sqrt(n). If the current divisor is i, the best possible way to take the series will be to consider i, 2*i, 3*i, …(m-1)*i, and their sum is s which is equal to i * (m*(m-1))/2 . The last number will be n-s.
Along with i being the divisor, n/i will be the other divisor so check for that also.
Take maximum of possible divisor possible (say r) which should be less then or equals to b and print the sequence as r, 2*r, … (m-1)*r, n—s.
If no such divisors are found simply output “-1”.
2 4 6 12 1 2 3 4 14 -1
Time complexity: O( sqrt (n) )
Auxiliary Space: O(1)
This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if any permutation of N equals any power of K
- Find smallest number n such that n XOR n+1 equals to given k.
- Find the number of pairs such that their gcd is equals to 1
- Array containing power of 2 whose XOR and Sum of elements equals X
- Number of Co-prime pairs from 1 to N with product equals to N
- Count of n digit numbers whose sum of digits equals to given sum
- Print all n-digit numbers whose sum of digits equals to given sum
- Smallest number greater or equals to N such that it has no odd positioned bit set
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- Minimum number of squares whose sum equals to given number n
- Largest Subset with GCD 1
- Largest subarray with GCD one
- Sum of Series (n^2-1^2) + 2(n^2-2^2) +....n(n^2-n^2)
- Sum of series 1*1! + 2*2! + ……..+ n*n!
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2