A GCD question
Title link: nowcoder 213804
To Niu Ke:
Topic
There are a bunch of numbers, you have to add them to the smallest possible number k, and make their gcd as large as possible.
Want you to output this k and the largest gcd at the end.
Ideas
This question adds one to all the numbers, and the difference between any two numbers is the same.
Let's look at gcd again. If the gcd of a bunch of numbers is x, then the absolute value of the difference between any two numbers must be a multiple of x.
Then we might as well find out these numbers after sorting, and combine the difference between every two numbers into a new sequence, the gcd of this sequence is the largest gcd they can have.
How much should k be the smallest?
That is to make each a multiple of the gcd value we find.
In fact, we only need to add the smallest to its multiple.
(Then of course if gcd is 1 1No need to add 1 )
Code
#include<cstdio>
#include<algorithm>
using namespace std;
int n, a[100010], re, zf, gcdd;
char c;
int read() {
zf = 1;
re = 0;
c = getchar();
while (c < '0' || c > '9') {
if (c == '-') zf = -zf;
c = getchar();
}
while (c >= '0' && c <= '9') {
re = re * 10 + c - '0';
c = getchar();
}
return re * zf;
}
bool cmp(int x, int y) {
return x < y;
}
int gcd(int x, int y) {
if (!y) return x;
return gcd(y, x % y);
}
int main() {
n = read();
for (int i = 1; i <= n; i++) {
a[i] = read();
}
sort(a + 1, a + n + 1, cmp);
gcdd = a[2] - a[1];
for (int i = 3; i <= n; i++) {
gcdd = gcd(gcdd, a[i] - a[i - 1]);
}
if (gcdd == 1) printf("1 0");
else printf("%d %d", gcdd, gcdd - (a[1] % gcdd));
return 0;
}