【codechef】Chef and Strange Formula(找规律,灵活题)

65 篇文章 0 订阅
27 篇文章 0 订阅


Input:
5 7
1 2 3 4 5

Output:
6

Explanation

  • F(1) = 1 * (1! + 1) = 2
  • F(2) = 1 * (1! + 2) + 2 * (2! + 2) = 3 + 8 = 11
  • F(3) = 1 * (1! + 3) + 2 * (2! + 3) + 3 * (3! + 3) = 4 + 10 + 27 = 41
  • F(4) = 1 * (1! + 4) + 2 * (2! + 4) + 3 * (3! + 4) + 4 * (4! + 4) = 5 + 12 + 30 + 112 = 159
  • F(5) = 1 * (1! + 5) + 2 * (2! + 5) + 3 * (3! + 5) + 4 * (4! + 5) + 5 * (5! + 5) = 794 F(1) + F(2) + F(3) + F(4) + F(5) = 2 + 11 + 41 + 159 + 794 = 1007 1007 modulo 7 = 6
有一个规律:1*1!+2*2!+...+n*n! = (n-1)!-1
可以转化F(x)=x*(1+2+...+x)+1*1!+2*2!+...+x*x!

x*x*(x+1)/2取模的时候要注意分奇偶情况:奇数时,/2和x[i]+1归一起;偶数时,/2和x[i]归一起
如果x>m,那么(x-1)!肯定含有一项是m,因此
(x-1)! = 0,(x-1)!-1 =-1;
http://www.codechef.com/problems/STFM/

#include <cstdio>
#include <cstring>
#include <iostream>
#define ll long long
using namespace std;
int x[10000001];
int fact[10000001];
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	ll max=0;
	for(int i=0;i<n;++i){
	 	scanf("%I64d",&x[i]);
		if(x[i]>max&&x[i]<m-1) //找出最大值(大于m-1直接不考虑(含有公因子m))
			max=x[i];
	}
	ll f=1,sum=0,t1,t2,t3;
	for(ll i=1;i<=max+1;++i){  //i-1的阶乘
		f*=i;
		f%=m;
		fact[i-1]=f;
	}
	for(int i=0;i<n;++i){
		if(x[i]>m||fact[x[i]]==0)
			sum+=m-1;  //sum-1
		else
			sum+=fact[x[i]]-1; 
		if(x[i]%2==0){   //x[i]为偶数,可以直接/2
			t1=(x[i]/2)%m;
			t2=x[i]%m;
			t3=(x[i]+1)%m;
			sum=sum+(((t1*t2)%m)*t3)%m; // x*x*(x+1)/2 
		}
		else{    //x[i]+1为偶数,可以/2
			t1=x[i]%m;
			t2=((x[i]+1)/2)%m;
			sum=sum+(((t1*t1)%m)*t2)%m; // x*x*(x+1)/2
			sum=sum%m;
		}
	}
	printf("%I64d\n",sum);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值