首页 > 其他 > 详细

Project Euler:Problem 74 Digit factorial chains

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

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

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

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