首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【LightOJ】1189 - Sum of Factorials(思维)

【LightOJ】1189 - Sum of Factorials(思维)

作者头像
FishWang
发布2025-08-27 11:42:48
发布2025-08-27 11:42:48
11300
代码可运行
举报
运行总次数:0
代码可运行

点击打开题目

1189 - Sum of Factorials

PDF (English)

Statistics

Forum

Time Limit: 0.5 second(s)

Memory Limit: 32 MB

Given an integer n, you have to find whether it can be expressed as summation of factorials. For given n, you have to report a solution such that

n = x1! + x2! + ... + xn! (xi < xj for all i < j)

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1018).

Output

For each case, print the case number and the solution in summation of factorial form. If there is no solution then print 'impossible'. There can be multiple solutions, any valid one will do. See the samples for exact formatting.

Sample Input

Output for Sample Input

4 7 7 9 11

Case 1: 1!+3! Case 2: 0!+3! Case 3: 1!+2!+3! Case 4: impossible

没有看到 “大众” 们的代码,不懂他们写的什么意思。

我当时看到了一个规律:后面一个数的阶乘总是大于等于前面的数的阶乘之和。

那么从最后往前走,如果给出的数大于了这个数的阶乘的2倍,那么肯定不成立。如果小于这个数的阶乘,那么继续往前扫,否则就选中这个数,然后减去它的阶乘,一直到这个数减为0.

代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define CLR(a,b) memset(a,b,sizeof(a))
#define LL long long
#define PI acos(-1.0)
LL fac[25];
bool flag;
LL n;
stack<int> s;
int main()
{
	int u;
	int Case = 1;
	fac[0] = 1;
	LL sum = 1;
	for (int i = 1 ; i <= 19 ; i++)
		fac[i] = fac[i-1] * i , sum += fac[i];
	scanf ("%d",&u);
	while (u--)
	{
		scanf ("%lld",&n);
		printf ("Case %d: ",Case++);
		if (n > sum)
		{
			puts("impossible");
			continue;
		}
		while (!s.empty())
			s.pop();
		flag = false;
		for (int i = 19 ; i >= 0 ; i--)
		{
			if (n < fac[i])
				continue;
			else if (n == fac[i])
			{
				s.push(i);
				flag = true;
				break;
			}
			else if (n > 2*fac[i])
				break;
			else
			{
				s.push(i);
				n -= fac[i];
			}
		}
		if (flag)
		{
			while (s.size() != 1)
			{
				printf ("%d!+",s.top());
				s.pop();
			}
			printf ("%d!\n",s.top());
			s.pop();
		}
		else
			puts("impossible");
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Input
  • Output
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档