码迷,mamicode.com
首页 > 其他好文 > 详细

Project Euler:Problem 74 Digit factorial chains

时间:2015-07-17 22:49:49      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:project euler   c++   

The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:

1! + 4! + 5! = 1 + 24 + 120 = 145

Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:

169 → 363601 → 1454 → 169
871 → 45361 → 871
872 → 45362 → 872

It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,

69 → 363600 → 1454 → 169 → 363601 (→ 1454)
78 → 45360 → 871 → 45361 (→ 871)
540 → 145 (→ 145)

Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.

How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?



#include <iostream>
#include <map>
using namespace std;

int factor[10] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };

int factnum(int n)
{
	int res = 0;
	while (n)
	{
		res += factor[n % 10];
		n /= 10;
	}
	return res;
}

int main()
{
	int count = 0;
	for (int i = 1; i <= 1000000; i++)
	{
		map<int, int>mp;
		mp[i]++;
		int tmp = i;
		while (true)
		{
			tmp = factnum(tmp);
			if (mp.find(tmp) == mp.end())
				mp[tmp]++;
			else
			{
				if (mp.size() == 60)
				{
					//cout << count << endl;
					count++;
				}
				break;
			}
		}
	}
	cout << count << endl;
	system("pause");
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Project Euler:Problem 74 Digit factorial chains

标签:project euler   c++   

原文地址:http://blog.csdn.net/youb11/article/details/46931487

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!