zoukankan      html  css  js  c++  java
  • uva11582

    The i’th Fibonacci number f(i) is recursively defined in the following way: • f(0) = 0 and f(1) = 1 • f(i + 2) = f(i + 1) + f(i) for every i ≥ 0 Your task is to compute some values of this sequence.

    Input

    Input begins with an integer t ≤ 10, 000, the number of test cases. Each test case consists of three integers a, b, n where 0 ≤ a, b < 2 64 (a and b will not both be zero) and 1 ≤ n ≤ 1000.

    Output

    For each test case, output a single line containing the remainder of f(a b ) upon division by n.

    Sample Input

    3

    1 1 2

    2 3 1000

    18446744073709551615 18446744073709551615 1000

    Sample Output

    1 21 250

    题意:巨大的斐波那契,所有的计算都是对n取模,不妨设f(i) = (f(i-1) + f(i-2))%n;则根据分析最多进行n*n次循环就会出现重复序列,然后用快速幂求a的b次方的后n位数就是其在循环中的位置,具体分析可见紫书。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    typedef unsigned long long ll;
    int f[1000010];
    int mod( ll a,ll b,int y){
        int t = 1;
        while(b){
            if(b%2 != 0){
                t = (a*t)%y;
                b--;
            }
            a = (a*a)%y;
            b /= 2;
        }
        return t;
    }
    //int f[1000010];
    int main()
    {
        ll a,b;
        int n,i,t,record;
        scanf("%d",&t);
        while(t--){
        	f[1] = f[2] = 1;
            cin>>a>>b>>n;
            if(a == 0 || n == 1){
                printf("0
    ");
                continue;
            }
            for(i = 3; i <= n*n+10; i++){
                f[i] = (f[i-1]+f[i-2])%n;
                if(f[i] == f[2] && f[i-1] == f[1]){
                    record = i-2;
                    break;
                }
            }
            int h = mod(a%record,b,record);
            printf("%d
    ",f[h]);
        }
        return 0;
    }
    

      

  • 相关阅读:
    AJAX 大全
    has value '1.8', but '1.7' is required
    VS2010官方下载地址
    win10桌面显示我的电脑
    使用 CAST
    for循环+canvas实现黑客帝国矩形阵
    C# Lambda
    win7系统部分便笺的元数据已被损坏怎么恢复
    SQL查询所有表,所有列
    truncate和delete之间有什么区别
  • 原文地址:https://www.cnblogs.com/clb123/p/10735260.html
Copyright © 2011-2022 走看看