hdu 1099通分

这题几年前就看过,一直没看懂啊。。。今天翻解题报告,才知道就是求n/1、n/2、n/3、...、n/(n-1)、n/n的和,并且以分数的形式表示,还算简单。

/*
 * hdu1099/win.cpp
 * Created on: 2012-7-27
 * Author    : ben
 */
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <functional>
#include <numeric>
#include <cctype>
using namespace std;
int gcd(int a, int b) {
    int r;
    while(b) {
        r = a % b;
        a = b, b = r;
    }
    return a;
}

int getbitlen(int n) {
    char str[300];
    sprintf(str, "%d", n);
    return strlen(str);
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("data.in", "r", stdin);
#endif
    int n, up, down, intpart;
    while(scanf("%d", &n) == 1) {
        intpart = up = 0;
        down = 1;
        for(int i = 1; i <= n; i++) {
            up = up * i + n * down;
            down *= i;
            int temp = gcd(up, down);
            up /= temp;
            down /= temp;
            temp = up / down;
            up -= temp * down;
            intpart += temp;
        }
        if(up == 0) {
            printf("%d\n", intpart);
        }else {
            int len = getbitlen(intpart);
            for(int i = 0; i <= len; i++) {
                putchar(' ');
            }
            printf("%d\n", up);
            printf("%d ", intpart);
            len = getbitlen(up) > getbitlen(down) ? getbitlen(up) : getbitlen(down);
            for(int i = 0; i < len; i++) {
                putchar('-');
            }
            putchar('\n');
            len = getbitlen(intpart);
            for(int i = 0; i <= len; i++) {
                putchar(' ');
            }
            printf("%d\n", (int)down);
        }
    }
    return 0;
}
posted @ 2012-07-27 13:34  moonbay  阅读(170)  评论(0编辑  收藏  举报