HDOJ1005:Number Sequence 快速数组幂

来源:互联网 发布:淘宝客免费跟发软件 编辑:程序博客网 时间:2024/06/04 23:34

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.

example

input:
1 1 3
1 2 10
0 0 0
output:
2
5

个人代码:

//超出内存限制 T_T#include <stdio.h>int f(int,int,int);int main(){    int A,B,n;    while(scanf("%d%d%d",&A,&B,&n)!=EOF){        if(A>=1&&B<=1000&&n<=100000000&&n>1){            int sum;            sum=f(n,A,B);            printf("%d\n",sum);        }        else if(A==0&&B==0&&n==0){            return 0;        }        else{            return -1;        }    }    return 0;}int f(int n,int x,int y){    if(n==1||n==2){        return 1;    }    else       return  (x*f(n-1,x,y)+y*f(n-2,x,y))%7;}

标准:

// 似乎有应用到找规律?...从第n个开始 就是重复的#include<stdio.h>int main(){    int a,b,n,i,arr[48];    while(scanf("%d %d %d",&a,&b,&n),a||b||n){        arr[1]=1;        arr[2]=1;        for(i=3;i<48;i++)            arr[i]=((a*arr[i-1]+b*arr[i-2])%7);        printf("%d\n",arr[n%48]);    }    return 0;}
原创粉丝点击