Back to Practice Dashboard
Competitive ProgrammingEasy

Minimum operations to make GCD multiple of k

Learn how to solve the 'Minimum operations to make GCD multiple of k' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function min_operations_gcd_k(arr, k) that returns the minimum number of operations to make the Greatest Common Divisor (GCD) of all elements in the array a multiple of k. In one operation, you can either increment or decrement any element of the array by 1.

Constraints
  • 1 <= len(arr) <= 10^5
  • 1 <= k <= 10^4
  • 1 <= arr[i] <= 10^9

Examples

Example 1
Input
min_operations_gcd_k([4, 5, 6], 5)
Output
2
Explanation

Increment 4 to 5 (1 op) and decrement 6 to 5 (1 op). The array becomes [5, 5, 5] whose GCD is 5, which is a multiple of 5.

Example 2
Input
min_operations_gcd_k([2, 3], 3)
Output
1
Explanation

Increment 2 to 3 (1 op). The array becomes [3, 3] whose GCD is 3, which is a multiple of 3.

Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor