首页 > 编程语言 > 详细

Project Euler 92:Square digit chains C++

时间:2017-08-23 22:41:06      阅读:363      评论:0      收藏:0      [点我收藏+]

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

  

Project Euler 92:Square digit chains C++

原文:http://www.cnblogs.com/ygtzds/p/7420541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!