题目
题目链接:http://poj.org/problem?id=1930
题目来源:《挑战》练习题
简要题意:给定一个无限循环小数的一部分,求最小分母的最简分数形式的分数。
数据范围: 9 位以内,保证有非
0
题解
无限不循环小数属于比较基础的内容,但是真做的时候还是有点乱,这题很好地稳固了基础。
首先这题的一个点是没有告诉你循环的位数,这个可以直接枚举。
之后就是这题需要分数运算,对此可以自己写个类来搞,有板直接上。
首先去考虑 abcd/9999 就是 0.abcdabcd⋯ ,无限循环部分可以看成循环了再除 10 的幂次去移位。
拆成两部分,前面的部分除 10 的幂次,后面的除全部 9 再去除
10 的幂次,两部分加起来就是答案了。
实现
需要注意边界不循环部分可以是 0 <script type="math/tex" id="MathJax-Element-9">0</script>,循环部分必须有。
分数的板是之前问王老板要的,总算是有了用处。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
LL powmod(LL a,LL b, LL MOD) {LL res=1;a%=MOD;for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;}
// head
char s[25];
struct Fraction {
LL x, y;
LL gcd(LL a, LL b) {
return b?gcd(b,a%b):a;
}
Fraction(LL x = 0, LL y = 1) {
if (y < 0) {
x = -x;
y = -y;
}
LL g = gcd(x < 0 ? -x : x, y);
this->x = x/g;
this->y = y/g;
}
void print() {
if (y==1) printf("%I64d", x);
else printf("%I64d/%I64d", x, y);
puts("");
}
Fraction operator +(const Fraction &o) const{
return Fraction(x*o.y+y*o.x,y*o.y);
}
Fraction operator -(const Fraction &o) const{
return Fraction(x*o.y-y*o.x,y*o.y);
}
Fraction operator *(const Fraction &o) const{
return Fraction(x*o.x,y*o.y);
}
Fraction operator /(const Fraction &o) const{
return Fraction(x*o.y,y*o.x);
}
bool operator ==(const Fraction &o) const{
return x*o.y==y*o.x;
}
bool operator <(const Fraction &o) const{
return x*o.y<y*o.x;
}
bool operator >(const Fraction &o) const{
return x*o.y>y*o.x;
}
bool operator >=(const Fraction &o) const{
return x*o.y>=y*o.x;
}
bool operator <=(const Fraction &o) const{
return x*o.y<=y*o.x;
}
bool operator !=(const Fraction &o) const{
return x*o.y!=y*o.x;
}
};
LL pow10[15];
LL a[15];
LL b[15];
int main()
{
pow10[0] = 1;
for (int i = 1; i < 15; i++) {
pow10[i] = pow10[i-1]*10;
}
int n;
while (scanf("%s", s) == 1) {
n = strlen(s);
if (n == 1) break;
Fraction ans(1, 1e18);
a[1] = b[n-3] = 0;
for (int i = 2; i < n-3; i++) {
a[i] = a[i-1]*10 + s[i]-'0';
}
for (int i = n-4; i > 1; i--) {
b[i] = b[i+1] + (s[i]-'0')*pow10[n-i-4];
}
for (int i = 1; i < n-4; i++) {
Fraction aa(a[i], pow10[i-1]);
Fraction bb(b[i+1], (pow10[n-i-4]-1)*pow10[i-1]);
Fraction temp = aa + bb;
if (ans.y > temp.y) {
ans = temp;
}
}
printf("%I64d/%I64d\n", ans.x, ans.y);
}
return 0;
}