天梯赛 L2-029 特立独行的幸福 (25 分)
根据某大佬的做法写的,记录一下自己的学习过程
#include<iostream>
using namespace std;
const int N = 1e4+10;
int a,b;
int p[N];
int res[N];
bool isPrime(int x){
if(x < 2) return false;
for(int i = 2; i < x / i; i++)
if(x % i == 0) return false;
return true;
}
int getSquare(int x){
int t = 0;
while(x){
t = t + (x % 10) * (x % 10);
x /= 10;
}
return t;
}
int find_root(int x){ // 找到最终指向的根如果这个数是幸福数,则最终一定会指到1,1的根就是自己
int root = x;
int cnt = 1;
while(p[root] != root){
root = p[root];
cnt++;
if(cnt > b) return -1;
}
return root;
}
bool isHappy(int x){ // 断a,b范围内否有数字指向x,即判断是否独立
for(int i = a; i <= b; i++) if(p[i] == x) return false;
return true;
}
int main(){
cin >> a >> b;
bool have = false;
for(int i = 1; i < N; i++) p[i] = getSquare(i); // //令所有数字指向自己的各位平方和
for(int i = a; i <= b; i++){
int cnt = 1;
if(find_root(i) == 1 && isHappy(i)){ // //如果找根能找到1,而且n到m没有数字指向它,就是特立独行的幸福数
cout <<i << " ";
int x = i;
while(getSquare(x) != 1){
x = getSquare(x);
cnt++;
}
if(isPrime(i)) cnt *= 2;
cout << cnt << endl;
have = true; // 记录有没有幸福数
}
}
if(!have) cout << "SAD" << endl;
return 0;
}
``