试题 历届试题 小数第n位

题目链接 http://lx.lanqiao.cn/problem.page?gpid=T456

要考虑无限循环小数的情况,否则会超时。

我们根据经验可以知道无限循环小数中循环位数的出现不会太晚,一般不会到50位(觉得不保险可以到500)。

于是我们可以用两个数组,第一个数组记录前50位小数,第二个数组记录循环位数(从第50位开始,50位我们可以保证循环已经开开始)。

然后根据上面思路模拟出发即可。

#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <iomanip>
using namespace std;
const int maxn = 1010;
typedef long long ll;

int main() {
    freopen("i.txt", "r", stdin);
    freopen("o.txt", "w", stdout);
    ll a, b, n;
    cin >> a >> b >> n;
    int arr[maxn], circle[maxn];
    // 必不可少!
    if(a > b) a %= b;
    // 先记录前50位
    for(int i = 1; i <= 50; i++) {
        int t = a*10 / b;
        arr[i] = t;
        a = a*10 % b;
    }
    int tmp = a, len = 0, cnt = 1;
    // 从51位寻找循环位数
    do {
        int t = a*10 / b;
        circle[cnt++] = t;
        len++;
        a = a*10 % b;
    } while(tmp != a);

    if(n <= 50) 
        cout << arr[n] << arr[n+1] << arr[n+2] << endl;
    else {
        int t = (n-50) % len;
        cout << circle[t % len] << circle[(t+1) % len] << circle[(t+2) % len] << endl;
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值