Fibonacci take the remainder divided by 10007

problem

Problem Description

Fibonacci recursion formulas for the number of columns: Fn = Fn-1 + Fn-2, where F1 = F2 = 1.

When n is relatively large, Fn is very great, and now we want to know, Fn is divided by the number 10007 is.

Input Format
Input contains an integer n.
Output Format
Output one line containing an integer representing the Fn remainder of the division of 10007.

Description: In this problem, the answer is to require Fn is divided by 10007, so we can figure this out as long as the remainder can be, without the need to calculate the exact value of Fn, then the result is calculated by dividing the number 10007 to take over direct calculation the remainder often than first calculate the original number and then take the remainder simple.

Sample input
10
Sample Output
55
Sample input
22
Sample Output
7704
Data size and convention
1 <= n <= 1,000,000。

solve

  Remainder Theorem present calculation: n% p = (a + b)% p = (a% p + b% p)% p, comparable distribution ratio, I take a count of p, this number can be seen as a + b, then the remainder is equal to a remainder taking the remainder plus p p b is taken and then the remainder of the p-taking. We only need to use an array to save the remainder of each Fn% 10007, small to large values ​​of n% p to recurrence of the array is the first n-1 Xiang.

package RuMenXunLian;

import java.util.Scanner;

public class Fibonacci {
    
    public static void main(String args[]){
        int n;
        final int num=10007;
        Scanner scanner =new Scanner(System.in);
        n = scanner.nextInt();
        if(n==1||n==2)
        {
            System.out.println(1);
        }else {
            int[] a = new int[n];
            a[0] = 1;
            a[1] = 1;
            for(int i=2;i<n;i++)
            {
                a[i] = (a[i-1]+a[i-2])%num;
            }
            System.out.println(a[n-1]);
        }
    }
}

Guess you like

Origin www.cnblogs.com/LieYanAnYing/p/12037622.html