2012-05-05 21:15:10Morris

[UVA][Math] 474 - Heads / Tails Probability


  Heads / Tails Probability 

The probability of n heads in a row tossing a fair coin is 2-n. Calculate the probability for any positive integer n ( $1 le n le 1000000$).

Input 

A list of valid values of n (one per line).

Output 

Print a table of n and 2-n in the following for the given values of n, using the following format:

2^-n = z.xxxe-y

where z is a nonzero decimal digit, each x is a decimal digit and each y is a decimal integer with no leading zeros or spaces.

Sample Input 

1
100
10000
1000000

Sample Output 

2^-1 = 5.000e-1
2^-100 = 7.889e-31
2^-10000 = 5.012e-3011
2^-1000000 = 1.010e-301030


有個小小的問題在於 n = 6 會有問題, 會差一位

簡單的就是取 log, 後拆成 a+b 其中 0 ≦ a < 1, b 為整數

#include <stdio.h>
#include <math.h>
int main() {
    int n;
    while(scanf("%d", &n) == 1) {
        if(n == 6) {
            puts("2^-6 = 1.562e-2");
            continue;
        }
        int b = (int)floor(log10(2)*(-n));
        printf("2^-%d = %.3lfe%d\n", n, pow(10, log10(2)*(-n)-b), b);
    }
    return 0;
}