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

UVA 766 - Sum of powers(伯努利数)

时间:2014-07-02 08:46:49      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   width   os   cti   

766 - Sum of powers


题意:求   bubuko.com,布布扣 转化成 bubuko.com,布布扣的各系数

思路:在wiki看了伯努利数的性质,
bubuko.com,布布扣 可以推成 bubuko.com,布布扣

然后B为伯努利数,有公式bubuko.com,布布扣

如此一来就可以去递推求出每项伯努利数了,然后在根据n去通分,求出每一项的答案,中间过程用到了分数的运算。

代码:
#include <stdio.h>
#include <string.h>

long long gcd(long long a, long long b) {
	if (!b) return a;
	return gcd(b, a % b);
}

long long lcm(long long a, long long b) {
	a = a / gcd(a, b) * b;
	if (a < 0) a = -a;
	return a;
}

struct Fraction {
	long long a, b;
	Fraction() {a = 0; b = 1;}
	
 	Fraction(long long x) {
		a = x; b = 1;
 	}
 	
 	Fraction(long long x, long long y) {
 		a = x; b = y;
  	}
  	
  	void deal() {
  		if (b < 0) {b = -b; a = -a;}
  		long long k = gcd(a, b);
  		if (k < 0) k = -k;
  		a /= k; b /= k;
    }
    
    Fraction operator+(Fraction p) {
    	Fraction ans;
    	ans.b = lcm(b, p.b);
    	ans.a = ans.b / b * a + ans.b / p.b * p.a;
    	ans.deal();
    	return ans;
   	}
   	
   	Fraction operator-(Fraction p) {
    	Fraction ans;
    	ans.b = lcm(b, p.b);
    	ans.a = ans.b / b * a - ans.b / p.b * p.a;
    	ans.deal();
    	return ans;
   	}
   	
   	Fraction operator*(Fraction p) {
   		Fraction ans;
   		ans.a = a * p.a;
   		ans.b = b * p.b;
   		ans.deal();
   		return ans;
   	}
   	
   	Fraction operator/(Fraction p) {
   		Fraction ans;
   		ans.a = a * p.b;
   		ans.b = b * p.a;
   		ans.deal();
   		return ans;
   	}
   	
   	void operator=(int x) {
   		a = x;
   		b = 1;
   	}
   	
   	void print() {
   		printf("%lld/%lld\n", a, b);
    }
};

const int N = 25;

Fraction B[N], C[N][N], a[N];
int n, t;
long long L;

void init() {
	for (int i = 0; i < N; i++) {
		C[i][0] = 1;
		C[i][i] = 1;
		for (int j = 1; j < i; j++) {
			C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
		}
 	}
	B[0] = 1;
	for (int i = 1; i <= 20; i++) {
		B[i] = 0;
		for (int j = 0; j < i; j++) B[i] = B[i] - C[i + 1][j] * B[j];
		B[i] = B[i] / C[i + 1][i];
 	}
}

int main() {
	init();
	scanf("%d", &t);
	while (t--) {
		L = 1;
		scanf("%d", &n);
		for (int i = 0; i <= n; i++) {
			a[i] = C[n + 1][i] * B[i] * Fraction(1, n + 1);
			L = lcm(L, a[i].b);
  		}
  		printf("%lld ", L);
  		a[1] = a[1] + 1;
  		for (int i = 0; i <= n; i++)
  			printf("%lld ", L / a[i].b * a[i].a);
		printf("0\n");
		if (t) printf("\n");
 	}
	return 0;
}


UVA 766 - Sum of powers(伯努利数),布布扣,bubuko.com

UVA 766 - Sum of powers(伯努利数)

标签:style   http   color   width   os   cti   

原文地址:http://blog.csdn.net/accelerator_/article/details/36216993

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