CF803C Maximal GCD

1 CF803C Maximal GCD

2 题目描述

时间限制 \(1s\) | 空间限制 \(256M\)

You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers \(a_1, a_2, ..., a_k,\) 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.

数据范围:\(1 ≤ n, k ≤ 10^{10}\)

3 题解

首先,答案一定是形如 \(gcd \times 1, gcd \times 2, ..., gcd \times (k+t)\) 的序列。这是因为序列的和一定是 \(gcd\) 的倍数,所以与 \(gcd\) 相乘的数的和最小时 \(gcd\) 最大。此时因为每个序列中的数都不相同且都为正数,那么为了使和最少,我们让每一个数都与上一个数差为 \(gcd\)。对于最后一个数,我们取尽可能多的 \(gcd\)。这样可以确保构造答案最优。

我们将答案变为 \(gcd \times (1 + 2 + ... + k + t)\)。此时我们发现,如果 \(n\) 可以整除 \(gcd\),那么答案一定满足,否则一定无法满足。我们就可以选择枚举 \(n\) 所有的因子,然后判断 \(\dfrac{n}{gcd}\) 是否大于 \((1 + 2 + ... + k)\),如果大于,那么答案一定成立,将当前 \(gcd\) 与最大的 \(gcd\)\(max\) 并更新。最后,我们只需要输出 \(gcd \times 1, gcd \times 2, ..., gcd \times (k + t)\) 即可。

4 代码(空格警告):

#include <iostream>
#include <cmath>
using namespace std;
#define int long long
int n, k, ans, gcd, last, maxn;
signed main()
{
    cin >> n >> k;
    if ((k+1)/2 > n/k)
    {
        cout << -1;
        return 0;
    }
    ans = k * (k-1) / 2;
    for (int i = sqrt(n); i >= 1; i--)
    {
        if (n % i == 0)
        {
            if (n / i - ans >= k)
            {
                if (maxn < i)
                {
                    last = n / i - ans;
                    gcd = i;
                    maxn = max(maxn, gcd);
                }
            }
            if (i - ans >= k)
            {
                if (maxn < n / i)
                {
                    last = i - ans;
                    gcd = n / i;
                    maxn = max(maxn, gcd);
                }
            }
        }
    }
    if (!last)
    {
        cout << -1;
        return 0;
    }
    for (int i = 1; i < k; i++)
    {
        cout << i * gcd << " ";
    }
    cout << last * gcd;
    return 0;
}

欢迎关注我的公众号:智子笔记

posted @ 2021-04-03 11:59  David24  阅读(53)  评论(0编辑  收藏  举报