AT2038 [ARC060B] 桁和 / Digit Sum

https://www.luogu.com.cn/problem/AT2038

考虑根号分治
对于 b < = n b<=\sqrt{n} b<=n 的,直接暴力判断

对于 b = n b=\sqrt{n} b=n 的,只有可能是个两位数,假设为 x b + y xb+y xb+y
联立可以得到
x + y = s , x b + y = n x+y=s,xb+y=n x+y=s,xb+y=n
做差可以得到 x ( b − 1 ) = n − s x(b-1)=n-s x(b1)=ns

枚举约数判断即可
注意求的是最小的(垃圾翻译)

code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll f(ll b, ll n) {
    if(n < b) return n;
    return f(b, n / b) + n % b;
}
ll n, s;
int main() {
    scanf("%lld%lld", &n, &s);
    if(n < s) {printf("-1"); return 0;}
    if(n == s) {printf("%lld", n + 1); return 0;}
    ll sq = ceil(sqrt(n));
    for(ll i = 2; i <= sq; i ++)
        if(f(i, n) == s) {
            printf("%lld", i);
            return 0;
        }
    for(ll x = sq; x >= 1; x --)
        if((n - s) % x == 0 && f((n - s) / x + 1, n) == s) {
            printf("%lld", (n - s) / x + 1);
            return 0;
        }
    printf("-1");
    return 0;
}

posted @ 2021-10-12 21:17  lahlah  阅读(34)  评论(0编辑  收藏  举报