Project Euler 26 Reciprocal cycles

来源:互联网 发布:linux中ll命的输出 编辑:程序博客网 时间:2024/05/04 06:56

Problem:
1/d 对应的小数部分 循环节最长 的那个d是多少?(d < 1000)
例如:
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
Solution:
求小数的过程就是商当作位数,把余数乘以10继续和d除,所以把商和余数看成一个整体的话,有循环节的充要条件就是存在两个整体 商和余数都对应相等,因为此时可以保证接下来的除法和之前是一样的。
note:
题目要求的是第几个,而不是最大长度是多少,embarrassed.

#include<iostream>#include<vector>using namespace std;struct node {    int integer, decimal;    node(int integerr, int decimall) : integer(integerr), decimal(decimall) {}    bool operator == (const node rhs) const {        return (integer==rhs.integer) && (decimal==rhs.decimal);    }};int main() {    vector<node> s;//save the digits    int maxs = 0, ans = 2;//the longest recurring cycle and its index    for(int d = 2; d < 1000; d++) {        s.clear();        int it = 10, dt;//the integer part and the decimal part        while (true) {            dt = it%d;  it = it/d;            if(dt == 0)//if it doesn't has recurring cycle                break;            vector<node>::iterator its = find(s.begin(), s.end(), node(it, dt));            if(its != s.end()) {//there is a recurring cycle.                if((int)(s.end()-its) > maxs) {                    maxs = (int)(s.end()-its);                    ans = d;                }                break;            }            else {                s.push_back(node(it, dt));                it = dt*10;            }        }    }    cout << ans << endl;    return 0;}
1 0