Project Euler 26 Reciprocal cycles(计算有理小数循环节长度)

来源:互联网 发布:算法精解 pdf 百度云 编辑:程序博客网 时间:2024/05/18 10:01

超级传送门:http://projecteuler.net/problem=26


算法的核心思想:在除法过程中如果某一状态的除数与被除数和前面某一状态的相等,则后续的除法计算陷入循环,循环节长度就是这两个状态的距离。

例子:计算1/7的循环节长度

状态1: 10/7  得1余3

状态2: 30/7  得4余2

状态3: 20/7  得2余6

状态4: 60/7  得8余4

状态5: 40/7  得5余5

状态6: 50/7  得7余1

状态7: 10/7  得1余3   与状态1相同,陷入循环


所以计算结果是0.142857142857142857.....  循环节是142857,长度为6.


代码如下:


#include <cstdio>#include <cstring>using namespace std;int calcRecurringCycleDigit(int u, int d) //  u/d{    int count = 0;    int hash[10100], latest[10100];    memset(hash, 0, sizeof(hash));    memset(latest, 0, sizeof(latest));    while (u % d)    {        count++;        while (u < d)            u *= 10;        int tmp = u / d;        if (hash[u])            return count - latest[u];        hash[u] = 1;        latest[u] = count;        u -= tmp * d;    }    return 0;}int main(){    int maxDigit = 0;    int ans = 0;    for (int i = 1; i < 1000; i++)    {        int digit = calcRecurringCycleDigit(1, i);        if (digit > maxDigit)        {            maxDigit = digit;            ans = i;        }    }    printf("%d\n", ans);    return 0;}


原创粉丝点击