Reciprocal cycles
A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.
Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
题目:
分子为1的分数称为单分数。分母是 2 到 10 的单分数用十进制表示如下:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
其中 0.1(6) 表示 0.166666...,因此它有一个长度为 1 的循环圈。可以看出 1/7 拥有一个 6 位的循环圈。
找出小于 1000 的数字 d,1/d 的十进制表示含有最长的循环圈。
这个题的解法,其实很简单就是模拟纸上除的竖式,通过竖式会发现,当余数为0时说明当前数没有循环,当同一个余数出现第二次时,说明这个数出现了循环;那么通过这个性质就可以去开始写代码,代码如下:
#include <stdio.h> int get_len(int x) {//模拟竖式的过程 int s = 1, num[1005] = {0}, len = 0;//num数组用来存当前余数是否出出现过 while (1) { s *= 10; s %= x; if (!s) return 0;//当模为0说明没有循环,那循环长度为0 if (num[s]) return len;//说明这个余数出现过开始第二次循环了,直接返回长度 num[s] = 1;//标记当前余数已经出现过 len++; } } int main() { int len = 0, ans = 1; for (int i = 2; i < 1000; i++) { int l = get_len(i);//获取当前数字的循环长度 if (l <= len) continue; len = l; ans = i; } printf("%d %d\n", len, ans); return 0; }
最终答案:983