程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> uva 10655,10655

uva 10655,10655

編輯:C++入門知識

uva 10655,10655


---恢復內容開始---

Given the value of a+b and ab you will have to find the value of an+bn

給出a+b和a*b的值,再給出n求a^n+b^n的值.

Input

The input file contains several lines of inputs. Each line except the last line contains 3 non-negative integers pq and n. Here p denotes the value of a+b andq denotes the value of ab. Input is terminated by a line containing only two zeroes. This line should not be processed. Each number in the input file fits in a signed 32-bit integer. There will be no such input so that you have to find the value of 00.

 多組測試數據,每組給出3個數,依次為p、q、n。p代表a+b,q代表a*b。當p和q都為0是這組數組不處理。

Output

For each line of input except the last one produce one line of output. This line contains the value of an+bn.  You can always assume that an+bfits in a signed 64-bit integer.

分析:

  定義f(n)=an+bn,則有f(n)∗(a+b)=(an+bn)∗(a+b)=an+1+abn+ban+bn+1=f(n+1)+abf(n−1), 所以f(n+1)=(a+b)f(n)−abf(n−1)

代碼:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxsize = 100;
typedef long long ll;
struct matrix{
    ll f[2][2];
};
matrix mul(matrix a,matrix b)
{
    ll i,j,k;
    matrix c;
    memset(c.f,0,sizeof(c.f));
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
            for(k=0;k<2;k++)
                c.f[i][j]+=a.f[i][k]*b.f[k][j];
    return c;
}

matrix ksm(matrix e,ll n)
{
    matrix s;
    s.f[0][0]=s.f[1][1]=1;
    s.f[1][0]=s.f[0][1]=0;
    while(n)
    {
        if(n&1)
            s=mul(s,e);
        e=mul(e,e);
        n=n>>1;
    }
    return s;
}
matrix e;
int main()
{
    ll p,q,n;
    while(cin>>p>>q>>n)
    {
        if(n==0)
        {
            cout<<2<<endl;
            continue;
        }
        e.f[0][0]=p;
        e.f[0][1]=1;
        e.f[1][0]=-q;
        e.f[1][1]=0;
        e=ksm(e,n-1);
        ll ans;
        ans=p*e.f[0][0]+2*e.f[1][0];
        cout<<ans<<endl;


    }
    return 0;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved