HDU 6217 BBP Formula 【快速幂】

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
HDU 6217 BBP Formula 【快速幂】_第1张图片
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

题意:

题目给你可以计算 π 的公式,让你求十六进制下的小数点后 π 的第 n 位,而不用计算前 n−1项。

思路:

HDU 6217 BBP Formula 【快速幂】_第2张图片

ac代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
//#include 
using namespace std;
typedef long long ll;

char print(int x)
{
    if (x >= 0 && x <= 9)
        return x + '0';
    return x + 55;
}
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 k, ll b)
{
    double res = 0;
    for (int i = 0; i <= n; i++)
        res += (qpower(16, n - i, 8 * i + b) * 1.0 / (8 * i + b));

    for (int i = n + 1; i <= n + 1000 + 1; i++)
        res += (powf(16, n - i) * 1.0 / (8 * i + b));
    return k * res;
}

int main()
{
    int t, n; cin >> t;
    int cas = 1;
    while (t--)
    {
        double ans = 0;
        cin >> n; n--;
        ans = bbp(n, 4, 1) - bbp(n, 2, 4) - bbp(n, 1, 5) - bbp(n, 1, 6);
        ans = ans - (int)ans;
        if (ans < 0)
            ans += 1.0;
        ans *= 16.0;
        char c;
        c = print(ans);
        printf("Case #%d: %d %c\n", cas++, n + 1, c);
    }
    return 0;
}

你可能感兴趣的:(快速幂,思维)