Uva--11582(数学,幂取模)

2014-08-30 23:39:21

Problem F: Colossal Fibonacci Numbers!

Oooh...pretty

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 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 < 264 (a andb will not both be zero) and 1 ≤ n ≤ 1000.

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

Sample input

3
1 1 2
2 3 1000
18446744073709551615 18446744073709551615 1000

Sample output

1
21
250

Zachary Friggstad

 

思路:找 fib[i] % n 这个数列的周期,再用快速幂算出 a^b % n 即可。(注意最好先把n = 1~1000都算好,然后输入一个,直接输出一个)。

  one trick:小于2^64的数要用unsigned long long。

  借鉴了别人的博客。

 

 1 /*************************************************************************
 2     > File Name: 11582.cpp
 3     > Author: Nature
 4     > Mail: 564374850@qq.com
 5     > Created Time: Sat 30 Aug 2014 03:18:33 PM CST
 6 ************************************************************************/
 7 
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cstdlib>
11 #include <cmath>
12 #include <vector>
13 #include <iostream>
14 #include <algorithm>
15 using namespace std;
16 typedef unsigned long long ull;
17 const int INF = 1 << 30;
18 
19 int t,n;
20 vector<int> fib[1005];
21 int cyc[1005];
22 ull a,b;
23 
24 void Pre_process(){
25     for(int p = 2; p <= 1000; ++p){
26         fib[p].push_back(0);
27         fib[p].push_back(1);
28         for(int i = 2; ; ++i){
29             fib[p].push_back((fib[p][i - 1] + fib[p][i - 2]) % p);
30             if(fib[p][i] == 1 && fib[p][i - 1] == 0){
31                 cyc[p] = i - 1;
32                 break;
33             }
34         }
35     }
36 }
37 
38 int Quick_pow_mod(ull x,ull y,int mod){
39     int ans = 1;
40     while(y){
41         if(y & 1)   ans = (int)((ans * x) % mod);
42         x = (x * x) % mod;
43         y >>= 1;
44     }
45     return ans;
46 }
47 
48 int main(){
49     Pre_process();
50     scanf("%d",&t);
51     while(t--){
52         scanf("%llu%llu%d",&a,&b,&n);
53         if(a == 0 || n == 1) printf("0\n");
54         else printf("%d\n",fib[n][Quick_pow_mod(a % cyc[n],b,cyc[n])]);
55     }
56     return 0;
57 }

 

posted @ 2014-08-30 23:42  Naturain  阅读(1203)  评论(0编辑  收藏  举报