TOJ3293 A Sequence of Numbers(快速幂取余)

本文介绍了一种高效计算指数运算的方法——快速幂算法,并通过一个具体的编程问题实例详细展示了该算法的应用过程。文章首先阐述了快速幂算法的基本原理,然后通过递归与非递归两种实现方式对比,解释了如何进行取模运算以避免整数溢出。
摘要由CSDN通过智能技术生成
Xinlv wrote some sequences on the paper a long time ago, they might be arithmetic or geometric sequences. The numbers are not very clear now, and only the first three numbers of each sequence are recognizable. Xinlv wants to know some numbers in these sequences, and he needs your help.

Input

The first line contains an integer  N , indicting that there are  N  sequences. Each of the following  N  lines contain four integers. The first three indicating the first three numbers of the sequence, and the last one is  K , indicating that we want to know the  K -th numbers of the sequence. You can assume 0 <  K  ≤ 10 9 , and the other three numbers are in the range [0, 2 63 ). All the numbers of the sequences are integers. And the sequences are non-decreasing.

Output

Output one line for each test case, that is, the  K -th number  module(%) 200907 .

Sample Input

2
1 2 3 5
1 2 4 5

Sample Output

5
16
快速幂思路(a^b mod n):
 
 
可以把b按二进制展开为:b = p(n)*2^n  +  p(n-1)*2^(n-1)  +…+   p(1)*2  +  p(0)
其中p(i) (0<=i<=n)为 0 或 1

这样 a^b =  a^ (p(n)*2^n  +  p(n-1)*2^(n-1)  +...+  p(1)*2  +  p(0))
               =  a^(p(n)*2^n)  *  a^(p(n-1)*2^(n-1))  *...*  a^(p(1)*2)  *  a^p(0)
对于p(i)=0的情况, a^(p(i) * 2^(i-1) ) =  a^0  =  1,不用处理
我们要考虑的仅仅是p(i)=1的情况
化简:a^(2^i)  = a^(2^(i-1)  * 2) = (  a^(  p(i)  *  2^(i-1)  )  )^2
(这里很重要!!具体请参阅秦九韶算法: http://baike.baidu.com/view/1431260.htm
利用这一点,我们可以递推地算出所有的a^(2^i)
当然由算法1的结论,我们加上取模运算:
a^(2^i)%c = ( (a^(2^(i-1))%c) * a^(2^(i-1)))  %c

于是再把所有满足p(i)=1的a^(2^i)%c按照算法1乘起来再%c就是结果 即二进制扫描从最高位一直扫描到最低位
递归写法:
//计算a^bmodn     
int modexp_recursion(int a,int b,int n)     
{    
    int t = 1;

    if (b == 0)
        return 1;

    if (b == 1)
         return a%n;

    t = modexp_recursion(a, b>>1, n);

    t = t*t % n;

    if (b&0x1)
    {    
        t = t*a % n;
    }

    return t;
 } 


//本题采用非递归写法
#include <cstdio>
#include <iostream>
using namespace std;
const int mod = 200907;

long long modexp(long long a,long long b);

int main(){
    int n;
    scanf("%d",&n);
    while (n--){
        long long a,b,c,k;
        scanf("%lld%lld%lld%lld",&a,&b,&c,&k);
        if (a + c == b * 2){
            cout << (a % mod + (k - 1) % mod * (c - b) % mod) % mod << endl;
        }else{
            cout << a % mod * modexp(b/a,k-1) %mod << endl;
        }
    }
    return 0;
}
long long modexp(long long a,long long b){
    long long res = 1;
    while (b){
        a %= mod;
        if (b & 1){
            res = res * a % mod;
            //cout << res;
        }
        a = a * a % mod;
        b = b >> 1;
        //cout << res;
    }
   // cout << res;
    return res;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值