CodeForces - 803C Maximal GCD

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值