HDOJ 1005 Number Sequence

Problem Description

A number sequence is defined as follows:
f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.
Given A, B, and n, you are to calculate the value of f(n).

Input

The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.

Output

For each test case, print the value of f(n) on a single line.

Sample Input

1 1 3
1 2 10
0 0 0

Sample Output

2
5

分析

迭代计算第N个数字时间会很慢,由于模运算的性质,运算次数依次除以2,如果是奇数,如果是偶数。

#include 
int main()
{
    int a,b,n;
    while(scanf("%d%d%d",&a,&b,&n)&&n!=0)
    {
        n=n-2;
        int f1=a,f2=b,f3=1,f4=0;
        if(n==-1)printf("%d\n",1);
        else if(n==0)printf("%d\n",1);
        else if(n==1)printf("%d\n",(a+b)%7);
        else
        {
            int ji[100];
            int length=0;
            while(n>1)
            {
                ji[length]=n%2;
                length++;
                n=n/2;
            }
            for(int i=length-1;i>=0;i--)
            {
                if(ji[i]%2==0)
                {
                    int temp1=f1,temp2=f2,temp3=f3,temp4=f4;
                    f1=((temp1%7)*(temp1%7)+(temp2%7)*(temp3%7))%7;
                    f2=((temp1%7)*(temp2%7)+(temp2%7)*(temp4%7))%7;
                    f3=((temp3%7)*(temp1%7)+(temp4%7)*(temp3%7))%7;
                    f4=((temp3%7)*(temp2%7)+(temp4%7)*(temp4%7))%7;
                }
                else
                {
                    int temp1=f1,temp2=f2,temp3=f3,temp4=f4;
                    f1=((temp1%7)*(temp1%7)+(temp2%7)*(temp3%7))%7;
                    f2=((temp1%7)*(temp2%7)+(temp2%7)*(temp4%7))%7;
                    f3=((temp3%7)*(temp1%7)+(temp4%7)*(temp3%7))%7;
                    f4=((temp3%7)*(temp2%7)+(temp4%7)*(temp4%7))%7;

                    temp1=f1;temp2=f2;temp3=f3;temp4=f4;
                    f1=((temp1%7)*(a%7)+(temp2%7))%7;
                    f2=((temp1%7)*(b%7))%7;
                    f3=((temp3%7)*(a%7)+(temp4%7))%7;
                    f4=((temp3%7)*(b%7))%7;
                }
            }
            printf("%d\n",(f1+f2)%7);
        }
    }
}

你可能感兴趣的:(HDOJ 1005 Number Sequence)