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.
Input
The first line consists of two numbers n and k (1 ≤ n, k ≤ 1010).
Output
If the answer exists then output k numbers — resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.
Example
Input
6 3
Output
1 2 3
Input
8 2
Output
2 6
Input
5 3
Output
-1
思路:最大公因子i一定也是为n的因子(k个i的倍数之和也一定为i的倍数),故从大到小枚举n的所有因子即可,枚举时有一定技巧,在注释中给出解释
#include <iostream>
#include <cmath>
using namespace std;
long long n, k;
int check(long long x)
{
if(x>n*2/k/(k+1))//必须用除法,不然会超时,估计跟数据太大有关
return 0;
for(int i = 1; i<=k-1; i++)
{
cout << x*i << " ";
n -= x*i;
}
cout << n << endl;
return 1;
}
int main()
{
while(cin >> n >> k)
{
for(long long i = 1; i*i<=n; i++)//减少循环次数,降低算法复杂度到1e5(n极大时,根号n到n的数据个数极多,会超时):n/i,枚举n到根号n的所有n的因子
{
if(n%i)//i是n的因子,则n/i也是n的因子
continue;
if(check(n/i))
return 0;
}
for(long long i = sqrt(n); i>0; i--)//枚举根号n到1的所有n的因子
{
if(n%i)
continue;
if(check(i))
return 0;
}
cout << "-1" << endl;
return 0;
}
return 0;
}