循環節定理+bsgs 哈爾濱理工ACM程序設計全國邀請賽(網絡同步賽) G.Recurring Decimal

G Recurring Decimal
Description
As we all know, any scores are can be written in an 
infinite recurring decimal or a finite decimal ,for 
example,1/7 can be written in 0.(142857).(recurring 
period is in the brackets).Now Give you a number x,
could you tell me the length of non-recurring period 
and recurring period of 1/x
Input
There are multiple cases in the input. 
In each case, there is a number x in a line(x is not 
greater than 2e9)
when x == 0 means end.
Output
For each test case, output two number a,b in a line 
separate with a space, mean the length of 
non-recurring period and recurring period.
Sample Input
1
2
3
0
Sample Output
0 0
1 0
0 1

題目就是說計算1/x的循環部分的長度與不循環部分的長度

明顯的模板題,參考這篇,http://blog.csdn.net/betwater/article/details/53543382

直接帶kuangbin的bsgs模板


#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MOD 76543
using namespace std;
int hs[MOD], head[MOD], next[MOD], id[MOD], top;
void insert(int x, int y)
{
    int k = x % MOD;
    hs[top] = x;
    id[top] = y;
    next[top] = head[k];
    head[k] = top++;
}
int find(int x)
{
    int k = x % MOD;
    for (int i = head[k]; i != -1; i = next[i])
        if (hs[i] == x)
            return id[i];
    return -1;
}
int BSGS(int a, int b, int n)
{
    memset(head, -1, sizeof(head));
    top = 1;
    //if (b == 1) return 0;

    int m = sqrt(n * 1.0), j;
    long long x = 1, p = 1;
    for (int i = 0; i < m; i++, p = p * a % n)
        insert(p * b % n, i);
    for (long long i = m; ; i += m)
    {
        if ((j = find(x = x * p % n)) != -1)
            return i - j;
        if (i > n)
            break;
    }
    return -1;
}
int main()
{
    //freopen("cin.txt","r",stdin);
    //freopen("cout2.txt","w",stdout);
    int x;
    while ( scanf("%d",&x) == 1  && x )
    {
        // 先算不循環部分
        int m2(0),m5(0);
        while ( x % 5 == 0 ) x /= 5 , m5++;
        while ( x % 2 == 0 ) x /= 2 , m2++;
        printf( "%d ",max(m2,m5));
        
        // 判斷一下x 然後直接BSGS 
        if ( x == 1 ){
            printf("%d\n",0);
        }else{
            int ans = BSGS(10,1,x);
            if ( ans == -1 )puts("0");
            else
                printf("%d\n",ans);
        }
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章