▼页尾

[Project Euler] Problem 26

这几日,一直忙于毕业设计,很久没有更新了

偶得闲暇,开始Level1的第一题

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.

我们知道,如果一个数的质因子全是2和5的话,这个数的倒数是不会无限循环的

如2,4,5,8,10

而一个数把质因子中的2和5除去后,得到一个数,我们称之为“基数”吧

这个数和它的基数的倒数循环的长度是相同的

比如说3和6的倒数的循环长度都是1

而怎么计算一个数的循环长度呢

只需要知道它能被多少长度的9整除就行了

3能被9整除,所以它的循环长度是1

7能被999999整除,商正好是循环体142857,所以它的循环长度是6

我想这一点大家应该很好理解吧

有前面的分析我们可以很容易得到这道题的解法

先求一个数的基数,如果是它本身,则计算它的循环长度

如果不是它自身,那它的循环长度等于基数的循环长度

我们规定1的循环长度是0,这样所以只含2,5为质因子的数的基数都为1,循环长度为0

我们来看看代码

#include <iostream>
usingnamespace std;

int getBase(int value);
int getCycle(constint value);

int main() {
int length[1000] = { 0 };
int tmp;
int max =0;
int value =0;
for (int i =2; i <1000; i++) {
tmp
= getBase(i);
if (tmp < i) {
length[i]
= length[tmp];
}
else {
length[i]
= getCycle(i);
}
}
for (int i =0; i <1000; i++) {
if(length[i]>max){
max
= length[i];
value
= i;
}
}
cout
<< value;
return0;
}

int getBase(int value) {
while (value %2==0) {
value
/=2;
}
while (value %5==0) {
value
/=5;
}
return value;
}

int getCycle(int value) {
if (9% value ==0) {
return1;
}
elseif (99% value ==0) {
return2;
}
elseif (999% value ==0) {
return3;
}
else {
int i =4;
int dividend =9999;
while (dividend % value !=0) {
i
++;
dividend
= dividend % value *10+9;
}
return i;
}
}

结果如下:

好啦,26题告一段落

posted @ 2011-03-23 15:42  xiatwhu  阅读(747)  评论(0编辑  收藏  举报
▲页首
西