1. 程式人生 > >hdu 6217 BBP Formula(數學問題)

hdu 6217 BBP Formula(數學問題)

BBP Formula

Time Limit: 16000/8000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others) Total Submission(s): 351    Accepted Submission(s): 206  

Problem Description

In 1995, Simon Plouffe discovered a special summation style for some constants. Two year later, together with the paper of Bailey and Borwien published, this summation style was named as the Bailey-Borwein-Plouffe formula.Meanwhile a sensational formula appeared. That is

π=∑k=0∞116k(48k+1−28k+4−18k+5−18k+6) For centuries it had been assumed that there was no way to compute the n-th digit of π without calculating allof the preceding n - 1 digits, but the discovery of this formula laid out the possibility. This problem asks you to calculate the hexadecimal digit n of π

immediately after the hexadecimal point. For example, the hexadecimalformat of n is 3.243F6A8885A308D313198A2E ... and the 1-st digit is 2, the 11-th one is A and the 15-th one is D.

Input

The first line of input contains an integer T (1 ≤ T ≤ 32) which is the total number of test cases. Each of the following lines contains an integer n (1 ≤ n ≤ 100000).

Output

For each test case, output a single line beginning with the sign of the test case. Then output the integer n, andthe answer which should be a character in {0, 1, · · · , 9, A, B, C, D, E, F} as a hexadecimal number

Sample Input

5

1

11

111

1111

11111

Sample Output

Case #1: 1 2

Case #2: 11 A

Case #3: 111 D

Case #4: 1111 A

Case #5: 11111 E

Source

【分析】

BBP公式:

【程式碼】

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
/*16^n-k很大,因為最後也是要除以(8k+t)的,所以先取餘,反正需要的只是那一位的答案的,所以這裡取餘可以避免精度問題*/
ll qpower(ll a,ll b,ll mod) 
{
	ll res=1;
	while(b)
	{
		if(b&1)res=a*res%mod;
		b>>=1;
		a=a*a%mod;
	}
	return res;
}
double bbp(int n,ll m,ll t)//bbp函式 
{
	double sum=0;
	for(int k=0;k<=n;k++)//這裡需要精度處理 
		sum+=qpower(16,n-k,8*k+t)/(double)(8*k+t);
	for(int k=n+1;k<=n+1001;k++)//不需要精度處理,將∞取一定範圍就好了 
		sum+=pow(16,n-k)/(double)(8*k+t);
	return sum*m;
}
int main()
{
	int t,ca=0;scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		n--;///////////
		double num=bbp(n,4,1)-bbp(n,2,4)-bbp(n,1,5)-bbp(n,1,6);
		num=num-(int)num;
		if(num<0)num++;
		num*=16;
		if(num <= 9)
            printf("Case #%d: %d %d\n",++ca,n+1,(int)num);
        else
            printf("Case #%d: %d %c\n",++ca,n+1,(int)num-10+'A');
	}
}