Maximal GCD
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal.
Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.
If there is no possible sequence then output -1.
InputThe first line consists of two numbers n and k (1 ≤ n, k ≤ 1010).
OutputIf the answer exists then output k numbers — resulting sequence. Otherwise output-1. If there are multiple answers, print any of them.
Examples6 3
1 2 3
8 2
2 6
5 3
-1
大致思路:最后所得的k个数是递增的,当是连续的k个整数时(即1,2,3,4,...,k),和sum(=k*(K+1)/2)最小。然后求n/sum的数值,i=n/sum可能是这k个数的最大公因数。判断依据是j=n%sum是否能被n/sum整除。若能则余数n%sum加到最后的那个数上面,输出。若不能,i-1,j+sum(相当于可最大公因数-1,余数增加一个sum),如此循环直到满足为止。
ps:注意数据最大值是否越界,k要满足的最大值是什么条件。
在j的值是i的a倍到a+1倍之间有很多没必要的循环,如何简化?
#include <stdio.h>
int main(){
long long n,k,i,j;
long long sum=0,count=1,a;
scanf("%lld%lld",&n,&k);
sum=k*(k+1)/2;
if(n<sum||k>1000000) printf("-1");
else {
i=n/sum;
j=n%sum;
if(j==0){
for(int h=1;h<=k;h++)
printf("%lld ",h*i);
}
else {
if(count*i>j){
a=(count*i-j)/(sum+count);
i=i-a;
j=j+sum*a;
}
for(;;j=j+sum,--i){
if(count*i < j&&j < (count+1)*i){
count++;
a=(count*i-j)/(sum+count);
i=i-a;
j=j+sum*a;
}
if(j>=i&&j%i==0){
for(int h=1;h<k;h++)
printf("%lld ",h*i);
printf("%lld",k*i+j);
break;
}
}
}
}
}
https://paste.ubuntu.com/p/ctyMDhjVr8/
如有错误,还请大家不吝赐教!