CodeForces - 803C 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.

Examples

Input

6 3

Output

1 2 3

Input

8 2

Output

2 6

Input

5 3

Output

-1

思路

题目转换:
N >= gcd * (1 + 2 + ….+ k)
N在符合上面的式子下求最大的gcd。
可以从1开始枚举gcd 直到刚好大于或等于N的时候停止,最后贪心输出答案

注意细节
  1. 求(1 + 2 + … + k)的时候可能会爆 long long
  2. 可以用sqrt枚举,降低复杂度

AC

#include<bits/stdc++.h>
#define N 10006
#define ll long long
using namespace std;
ll n, k, limit;
int judge(ll x) {   //判断此时的gcd是否合适 
    if(limit <= x)  return 1;
    else    return 0;   
}
int main() {
//  freopen("in.txt", "r", stdin);
    while (scanf("%lld%lld", &n, &k) != EOF) {
        limit = (1 + k) * k / 2;      
        if (k > 141421 || limit > n){   //特判不符合条件,limit 也可能爆long long
            printf("-1\n");
            continue;
        }       
        if (limit == n) {   //特判相等 答案:1--k 
            for (ll i = 1; i <= k; i++) 
                printf("%d ", i);
            printf("\n");
        }else {
            ll gcd;
            for (ll i = 1; i <= sqrt(n); i++) { //每次找n的因子,sqrt降低复杂度,否则1e10 
                if (n % i == 0) {
                    if (judge(i)) { //此时使得 gcd = n / i 最大,即为答案  
                        gcd = n / i;
                        break;
                    }
                    if (judge(n / i)) { //gcd从小找,找到不合适的就退出 
                        gcd = i;
                    }else {
                        break;
                    }
                }
                //同理也可以写成
//              if (n % i == 0) {
//                  if (i >= limit) {
//                      gcd = n / i;
//                      break;
//                  };
//                  if(n / i >= limit) {
//                      gcd = i;
//                  }   
//              } 
            }
            //贪心输出答案,前K - 1项为 1*gcd到k-1*gcd 
            ll temp = n / gcd;
            for(ll i = 1; i < k; i++) { //输出前K项 
                printf("%lld ", gcd * i);
                temp -= i;
            }
            printf("%lld\n", gcd * temp);   //输出最后一项
        }
    }   
    return 0;
}

猜你喜欢

转载自blog.csdn.net/henuyh/article/details/80220310
今日推荐