Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8020
  • 博文数量: 5
  • 博客积分: 353
  • 博客等级: 一等列兵
  • 技术积分: 60
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-10 14:00
文章分类
文章存档

2010年(5)

我的朋友
最近访客

分类:

2010-07-15 20:34:31

计算 1/x后第n位小数的值,其中x为32位非负整数,n为64位非负整数。

 

#include <stdio.h>

#include <stdlib.h>
#include <map>
#include <vector>

using namespace std;

static int doDiv(int dividant, int divisor, long long n)
{
  vector<int> result;
  map<int, int> repeat;
  int pos = 0;
  int loop_start = 0;
  int loop_end = 0;

  while (true) {
    if (repeat.find(dividant) != repeat.end()) {
      loop_start = repeat[dividant];
      loop_end = pos;
      break;
    }
    repeat.insert(make_pair(dividant, pos++));
    result.push_back(dividant / divisor);
    dividant = dividant % divisor;
    dividant *= 10;
  }
  int loop_len = loop_end - loop_start;
  if (n >= (long long) loop_start) {

    /* be ware of the type cast here. Sometimes the compiler might not do this quite well even if this code segment seems to work whatever */
    int offset = (n - loop_start) % loop_len + loop_start;
    return result[offset];
  } else {
    return result[n];
  }
  
}

int div(int x, long long n)
{
  if (x <= 0) return -1;
  return doDiv(1, x, n);
}

int main()
{
  int x;
  long long n;
  scanf("%d%lld", &x, &n);
  printf("%d\n", div(x, n));
  return 0;
}


阅读(430) | 评论(0) | 转发(0) |
0

上一篇:猜数字

下一篇:最长双调序列

给主人留下些什么吧!~~