422 字
2 分钟
Friendly-Numbers
题面
For an integer , we call another integer friendly if the following condition holds:
- , where is the sum of the digits of .
For a given integer , determine how many friendly numbers it has.
Input
Each test contains multiple test cases. The first line contains the number of test cases (). The description of the test cases follows.
Each test case consists of a single line containing one integer ().
Output
For each test case, output one integer — the answer to the problem.
思路
对题目所给的式子变形可以得到:
也就是求符合条件的 的个数
是输入,已经给出,我们只需要确定 即可
进行如下推理:
若 有 位,则
NOTE因为 表示 各位上的和,而每个数字位最大值为9
而注意到,当 时,
此时有:
明显不符合题目条件:
因此, 最多只有10位
根据上面的推论,不难得到:
因此可以得到 的上界:
因此,我们只需要暴力枚举 内范围的数,看他们是否满足条件即可,满足给对应计数器加一,否则不进行操作
代码
#include <bits/stdc++.h>
using namespace std;
int calc(int num) { string str = to_string(num); int result = 0; for (auto ch: str) { result += ch - '0'; } return result;}
int main() { int t; cin >> t;
while (t --) { int x; cin >> x; if (x == 1) cout << 0 << endl; else { int count = 0; for (int y = x + 1; y < x + 91; y ++) { int d = calc(y); if (y - d == x) { count ++; } } cout << count << endl; } }} Friendly-Numbers
https://github.com/posts/friendly-numbers/