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
- Number of Co-prime pairs from 1 to N with product equals to N
- Smallest number greater or equals to N such that it has no odd positioned bit set
- Print all n-digit numbers whose sum of digits equals to given sum
- Count of n digit numbers whose sum of digits equals to given sum
- Minimum number of squares whose sum equals to given number n
- Largest Subset with GCD 1
- Largest subarray with GCD one
- Largest Even and Odd N-digit numbers
- Largest subsequence having GCD greater than 1
- Product of N with its largest odd digit
- Find the largest possible k-multiple set
- Find the largest multiple of 2, 3 and 5