UVa 332 - Rational Numbers from Repeating Fractions

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

Solution

為了避免精度問題將小數點後用字串存下後轉 int。

此時為了把循環的部分刪掉:

$0.3\overline{18} = \frac{318.\overline{18}-3.\overline{18}}{10^3-10^{(3-2)}} = \frac {315}{990} = \frac {7}{22}$

上面 10 的指數部分 3 為小數點長度,2 是循環長度。
(意義同等題目給的式子)

分子 = n - n / (int)pow(10, j);
分母 = (int)pow(10, len) - (int)pow(10, len - j);

因為我們一開始就將它存成整數了,所以分子部分可以直接減,n / (int)pow(10, j) 就是直接把循環部份去掉。
最後再找 GCD 約分即可。

要特別注意不是循環小數和 0 0.0 的輸出。

Code

UVa 332
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include<cstdio>
#include<cmath>
#include<cstring>

inline int GCD(int a, int b)
{
while (b)
{
int t = a%b;
a = b;
b = t;
}

return a;
}
inline int to_num(char* str)
{
int n = 0;
for (int i = 0; str[i]; i++)
n = n * 10 + str[i] - '0';
return n;
}
int main()
{
int j, Case = 1;
while (scanf("%d", &j) && j != -1)
{
char str[10];
scanf("%*d.%s", str);

int count = 0, n, temp, len = strlen(str), gcd;
temp = n = to_num(str);

int a, b;//分子,分母
if (j)
{
while (temp)
{
count++;
temp /= 10;
}

a = n - n / (int)pow(10, j);
b = (int)pow(10, len) - (int)pow(10, len - j);
gcd = GCD(a, b);
printf("Case %d: %d/%d\n", Case++, a / gcd, b / gcd);
}
else
{
if (n)
{
a = n;
b = pow(10, len);
gcd = GCD(a, b);
printf("Case %d: %d/%d\n", Case++, a / gcd, b / gcd);
}
else//0 0.0
printf("Case %d: 0/1\n", Case++);
}
}

return 0;
}