A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?
本题求得是数字 的数位平方和为89 的个数。
很简单,暴力大法好。
剪枝是必要的,要不会吃不消。
数字末为89的链下处简称89链
一条数链中 的数字无非是新数字和 已出现过的数字,89链标记已出现过的数字。
在求链过程中,出现已标记的数字,那么该链必定可到达89。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int q(int x)
{
return x*x;
}
int f(int x)
{
int s=0;
while(x>0)
{
s+=q(x%10);
x/=10;
}
return s;
}
int vis[10000000];
int main()
{
int cnt=0;
for(int i=2;i<10000000;i++)
{
int temp=0;
int c=i;
while(c!=1)
{
if(c==89||vis[c]){
temp=1;
cnt++;
break;
}
c=f(c); }
if(temp==1) //如是89链,则标记数字
{
int c=i;
while(c!=1&&!vis[c])
{
if(c==89){
temp=1;
break;
}
c=f(c);
vis[c]=1;
}
}
} cout<<cnt<<endl;
}