Bob And GCD
Practice
3.8 (16 votes)
Ad Hoc
Algorithms
Basic programming
Easy
Greedy algorithms
Problem
44% Success 8150 Attempts 20 Points 2s Time Limit 256MB Memory 1024 KB Max Code

Bob has an array A of size N. He doesn't like arrays in which the \(GCD\) of all elements is not K. He can perform multiple operations on an array. In each operation, he can either increase or decrease the value of an element by 1.
You have to tell the minimum operation Bob will take to make \(GCD\) of all elements in an array equal to K or any multiple of K?

Note: The smallest value up to which you can decrease any element is 1. You cannot make any element smaller than 1.

GCD here is Greatest Common Divisor.

Input Format

The first line contains T, the number of test cases.

For Each Testcase :
The first line contains 2 integers - K and N respectively, separated by a space.
The second line contains N integers, separated by a space, in order of their position in array.

Input Constraints

\( 1 \le T \le 10 \)
\( 1 \le N \le 10^{6} \)
\( 1 \le A[i] \le 10^{6} \)
\( 1 \le K \le 10^6 \)

Output Format

For each test case, print minimum number of operations Bob take in a new line.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
8 votes
Tags:
AlgorithmsBasics of Greedy AlgorithmsC++Greedy Algorithms
Points:20
12 votes
Tags:
AlgorithmsEasyGreedy AlgorithmsString Manipulationsorting
Points:20
4 votes
Tags:
SetAlgorithmsBasics of Greedy AlgorithmsGreedy Algorithms