跳到正文

题解

P12334

Nightsky_Stars约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年4月30日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 2 分钟
获赞
3
题目
P12334

版本

  1. v1当前

思路:

设 f(x)f(x) 为 xx 的数位和。

因为 x=∑i=0ai10ix=\displaystyle \sum_{i=0}a_i10^{i},aia_i 为 xx 中的各个数位。又因为 10≡1(mod9)10 \equiv 1 \pmod{9},所以 10i≡1i(mod9)10^i \equiv 1^i \pmod{9},所以 f(x)≡x(mod9)f(x) \equiv x \pmod{9}。

因为 f(x)≡x(mod9)f(x) \equiv x \pmod{9},所以 f(x2)≡x2(mod9)f(x^2) \equiv x^2 \pmod{9},又可以推到 x2≡f(x)2(mod9)x^2 \equiv f(x)^2 \pmod{9}。所以 f(x2)≤f(x)2f(x^2) \le f(x)^2。

所以我们可以从 ⌈y⌉\lceil \sqrt{y} \rceil 枚举到 ⌈y+9⌉\lceil \sqrt{y}+9 \rceil。第一个合法的答案就是最小值,如果没有合法的,输出 −1-1 即可。

CODE:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
	#ifdef ONLINE_JUDGE
	ios::sync_with_stdio(0);
	#endif
	cin.tie(0);
	cout.tie(0);
	ll y;
	cin>>y;
	for(ll i=sqrtl(y-1)+1;i<=sqrt(y-1)+1+10;i++){//注意是向上取整
		if(i*i%9==y%9){
			cout<<i<<"\n";
			#ifndef ONLINE_JUDGE
			system("pause");
			#endif
			return 0;
		}
	}
	cout<<"-1\n";
	#ifndef ONLINE_JUDGE
	system("pause");
	#endif
	return 0;
}
原文