【light-oj】-1189 - Sum of Factorials(思维,数学)

1189 - Sum of Factorials
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



题意:把一个数写成n个数阶乘相加的形式。

题解:规律:一个数的阶乘总是大于等于前面数阶乘的和

把n写成几个数阶乘和的形式:若n>m!  n-=m!,继续判断m前的数,直到循环到达0后结束。

最后若n==0,就可以,否则不可以。

AC代码 1:

#include<cstdio> 
#include<cstring>
#include<stack> 
#include<algorithm>
using namespace std;
#define LL long long 
LL n;
LL fac[25];
LL sum=1;
void getfac()
{
	fac[0]=1;
	for(int i=1;i<=19;i++)
	{
		fac[i]=i*fac[i-1];
		sum+=fac[i]; 
	}
}
int main()
{
	getfac();
	int u,ca=1;
	scanf("%d",&u);
	while(u--)
	{
		bool flag=false;
		stack<int> sk;
		scanf("%lld",&n);
		printf("Case %d: ",ca++);
		if(n>sum)
		{
			printf("impossible\n");
			continue;
		}
		while(!sk.empty())
			sk.pop();
		for(int i=19;i>=0;i--)
		{
			if(n<fac[i])
				continue;
			else if(n==fac[i])
			{
				sk.push(i);
				flag=true;
				break;
			}
			else if(n>2*fac[i])
				break;
			else
			{
				sk.push(i);
				n-=fac[i];
			}
		}
		if(!flag)
		 	printf("impossible\n");
		else
		{
			while(sk.size()!=1)
			{
				printf("%d!+",sk.top());
				sk.pop();
			}
			printf("%d!\n",sk.top());
			sk.pop();
		}
	}
	return 0;
}

AC代码 2:

#include<cstdio>
#define LL long long
LL fac[22];
int a[22];
int main()
{
	int u,ca=1;
	scanf("%d",&u);
	fac[0]=1;
	for(int i=1;i<=19;i++)
		fac[i]=i*fac[i-1];
	while(u--)
	{
		LL n;
		int k=1;
		scanf("%lld",&n);
		printf("Case %d: ",ca++);
		for(int i=19;i>=0;i--)
		{
			if(n>=fac[i])
			{
				a[k++]=i;
				n-=fac[i];
			}		
		}
		if(n==0)	
		{
			for(int i=k-1;i>1;i--)
				printf("%d!+",a[i]);
			printf("%d!\n",a[1]);
		}
		else
			puts("impossible");
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值