Project Euler 92:Square digit chains C++

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 → 11
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;
}

  

转载于:https://www.cnblogs.com/ygtzds/p/7420541.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值